线程优先级

public class Thread5ThreadPriority
{
	private static Thread threadaa;
	private static Thread threadbb;
	private static Thread threadcc;
	public Thread5ThreadPriority()
	{
		threadaa=new Thread(new Runnable()
		{
			
			@Override
			public void run()
			{
				int i=0;
				for(;i<5;i++)
				{
					System.out.println("lotaa: "+i);
					
				}
				
			}
		});
		threadbb=new Thread(new Runnable()
		{
			
			@Override
			public void run()
			{
				int i=0;
				for(;i<5;i++)
				{
					System.out.println("lotbb: "+i);
					
				}
				
			}
		});
		threadcc=new Thread(new Runnable()
		{
			
			@Override
			public void run()
			{
				int i=0;
				for(;i<5;i++)
				{
					System.out.println("lotcc: "+i);
					
				}
				
			}
		});
		
		
		
		threadaa.setPriority(1);
		threadaa.setName("threadaa");
		threadaa.start();
		threadbb.setPriority(5);
		threadbb.setName("threadbb");
		threadbb.start();
		threadcc.setPriority(5);
		threadcc.setName("threadcc");
		threadcc.start();
		
		
	}
	public  static void main(String[] args)
	{
		
		new Thread5ThreadPriority();
	}

}


每次执行程序,发现优先级的设置并没有完全控制线程的执行顺序。

搜索网上的解释:

1.线程的调度由操作系统负责,即使是编译器也没办法完全包办。也即是说,运行时轮到哪个线程运行,完全由操作系统决定,优先级高的,只是轮到机会高一些,并非完全独占CPU运行;优先级低的也并非要等高优先级的线程运行完才能轮到,相对来说,轮到的机率低一些。

2.java中线程优先级较高的并不一定首先运行,只是首先运行的概率比较大。代码中有四个线程,优先级分别为10,10,4,3 。运行结果显示,优先级为10的两个线程在绝大部分情况下是先运行的,不过也有例外。在两个优先级为10的线程中,运行的先后顺序貌似是随机的。优先级为4和3的两个进程也是如此。




多线程执行顺序图整理如下:微笑








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值