线程的优先级机制(三)

2022/3/27 23:23:41

本文主要是介绍线程的优先级机制(三),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

    在多线程的机制下,如果执行的任务非常多,那么这个时候就需要考虑线程的优先级的任务信息。在Java的

应用程序中,优先级分为1-10,最高时优先级是10,最低的优先级是1,其中默认的优先级是5。只所以设置线程

优先级考虑的点是在资源出现瓶颈的情况下,这个时候需要执行的任务非常多,那么也就涉及一个问题,那么任

务先执行,那个任务后执行,这个时候优先级就显得尤为重要,这个时候优先级高的任务就会先执行,优先级低

的任务就会后执行。当然如果是在资源不那么稀缺少的情况下,这个时候任务的执行并不是说优先级高的优先

就会执行,而是看那个任务执行的快就会优先执行。优先级主要是会资源比较稀缺的情况下能够体现出它的实际

应用。下面具体一个具体的案例代码演示线程优先级的设置信息,具体案例代码如下:

package com.example.blog;

public class ThreadPriority
{
	public  static  int count=0;

	public static void main(String[] args)
	{
		Thread thread1=new Thread(new PriorityDemo());
		Thread thread2=new Thread(new PriorityDemo());
		Thread thread3=new Thread(new PriorityDemo());

		thread1.setPriority(8);
		thread1.setName("线程一");
		thread1.start();

		thread2.setPriority(10);
		thread2.setName("线程二");
		thread2.start();

		thread3.setPriority(2);
		thread3.setName("线程三");
		thread3.start();

		try{
			Thread.sleep(3000);

		}catch (Exception e){
			e.printStackTrace();
		}
		System.out.println("计算结果信息:"+ThreadPriority.count);
	}
}

class  PriorityDemo implements  Runnable
{
	@Override
	public void  run()
	{
		for(int i=0;i<10;i++)
		{
			ThreadPriority.count++;
		}
		System.out.println("线程名称:"+Thread.currentThread().getName());
	}
}

在如上代码中,如果按照线程的优先级,那么线程执行的顺序是线程二,线程一,线程三,但是

实际在执行的并不是这样的,这主要是因为目前资源并不是在一个瓶颈的情况下。



这篇关于线程的优先级机制(三)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程