如何优雅地调控并发世界的秩序?

Java所有的线程在运行前都会保持在就绪状态,哪个线程的优先级高,哪个线程就有可能会先执行。

Java程序中有最高、中等、最低3种优先级,使用setPriority方法可以设置一个线程的优先级。

示例1:演示3种不同优先级的线程执行结果

public class TaskPriority implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + "运行,i=" + i);
    }
  }
}


// 测试类
public class TaskPriorityTest {
public static void main(String[] args) {
    Thread ta = new Thread(new TaskPriority(),"线程A");
    Thread tb = new Thread(new TaskPriority(),"线程B");
    Thread tc = new Thread(new TaskPriority(),"线程C");
    
    ta.setPriority(Thread.MAX_PRIORITY);  //设置A线程的优先级为最高
    tb.setPriority(Thread.NORM_PRIORITY);  //设置B线程的优先级为中等
    tc.setPriority(Thread.MIN_PRIORITY);  //设置C线程的优先级为最低
    
    ta.start();
    tb.start();
    tc.start();
  }
}


程序运行结果:
线程A运行,i=1
线程B运行,i=1
线程C运行,i=1
线程A运行,i=2
线程B运行,i=2
线程C运行,i=2
线程A运行,i=3
线程B运行,i=3
线程C运行,i=3


再次运行结果:
线程C运行,i=1
线程B运行,i=1
线程A运行,i=1
线程B运行,i=2
线程C运行,i=2
线程A运行,i=2
线程C运行,i=3
线程B运行,i=3
线程A运行,i=3

通过以上的程序运行结果可以看到,虽然线程可以设置优先级来决定哪个线程先运行,实际上哪个线程先执行是由CPU的调度决定的,并不是高优先级的线程一定会先执行。

示例2:获取主方法的优先级

使用getPriority方法可以获取一个线程的优先级。

d5b4651d5aa16a9ee2cd1e6839233d34.png

public class GetPriorityTest {
public static void main(String[] args) {
    System.out.println("主方法的优先级是:" + Thread.currentThread().getPriority());
  }
}


程序运行结果:
主方法的优先级是:5

以上程序说明,主方法main线程的优先级常量是5,从上面的表格中可以看出,5代表中等优先级。因此说主线程的优先级是中等级别,一般情况下,线程默认的优先级就是中等级别。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值