编程语言
首页 > 编程语言> > Java面向对象高级部分——Java运行需要的线程(四十四)

Java面向对象高级部分——Java运行需要的线程(四十四)

作者:互联网

通过程序发现,主函数本身是一个线程,那么java运行的时候,最少需要几个线程?

至少两个:

·main

·垃圾回收机制(gx)

线程的休眠:让线程休眠一段时间,什么事情都不干

package obc18;

public class OopDemo02 {
      public static void main(String[] args) {
		System.out.println("休眠之前");
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("休眠之后");
	}
}

线程的优先级:

·static int MAX_PRIORITY 最高优先级

·static int MIN_PRIORITY 最低优先级

·static int NORM_PRIORITY 默认优先级

package obc18;

public class OopDemo03 {
      public static void main(String[] args) {
		ThreadDemo02 th = new ThreadDemo02();
		Thread th1 = new Thread(th,"张三");
		Thread th2 = new Thread(th,"李四");
		Thread th3 = new Thread(th,"王五");
		th1.setPriority(Thread.MAX_PRIORITY);
		th2.setPriority(Thread.NORM_PRIORITY);
		th3.setPriority(Thread.MIN_PRIORITY);
		th1.start();
		th2.start();
		th3.start();
	}
}

以上代码发现设置了优先级之后也并不一定是按照优先级执行线程,事实上优先高仅仅代表能过获得的资源更多,而这并不能保证,线程的运行一定能够优先。

package obc18;

public class OopDemo02 {
      public static void main(String[] args) {
		System.out.println(Thread.currentThread().getPriority());
	}
}

main函数的默认优先级通过代码发现是默认级别。

标签:优先级,Java,Thread,四十四,PRIORITY,线程,static,public
来源: https://blog.csdn.net/weixin_41830242/article/details/122240689