通过设置优先级来执行线程执行 [英] Thread execution ordering by setting priority

查看:121
本文介绍了通过设置优先级来执行线程执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已按以下顺序设置线程的优先级

I have set thread's priority in below order

A然后是B然后C。但是当我在程序运行时,有时B会在A之前运行。
I我不理解这个执行,因为我将B的优先级设置为低于A的优先级。

A then B then C .But when I am running below program sometimes B runs before A. I don't understand this execution as I set B's priority less then A's priority.

public class AThread implements Runnable{
    public void run(){
    System.out.println("In thread A");
   }}

  public class BThread implements Runnable {
      public void run(){
    System.out.println("In thread B");  
    } 
   }

 public class CThread implements Runnable {

 public void run(){

    System.out.println("In thread C");

 }

}


 public class ThreadPriorityDemo {

   public static void main(String args[]){

    AThread A = new AThread();
    Thread tA = new Thread(A);


    BThread B = new BThread();
    Thread tB = new Thread(B);

    CThread C = new CThread();
    Thread tC = new Thread(C);

    tA.setPriority(Thread.MAX_PRIORITY);
    tC.setPriority(Thread.MIN_PRIORITY);
    tB.setPriority(tA.getPriority() -1);


    System.out.println("A started");
    tA.start();

    System.out.println("B started");
    tB.start();

    System.out.println("C started");
    tC.start();

}       

}

推荐答案

线程优先级可能不是您认为的那样。

Thread priorities are probably not what you think they are.

线程的优先级是对操作系统的推荐在涉及这两个线程的任何调度或CPU分配决策点中优先选择一个线程而不是另一个线程。但是如何实现它取决于操作系统和JVM实现。

A thread's priority is a recommendation to the operating system to prefer one thread over another in any scheduling or CPU allocation decision point where these two threads are involved. But how this is implemented depends on the operating system and the JVM implementation.

JavaMex 对线程优先级进行了很好的讨论。要点是:

JavaMex has a nice discussion of thread priorities. The gist is that:


  1. 优先权可能完全无效。

  2. 优先级仅为一个计算的一部分,指示调度。

  3. 在实践中,可以将不同的Java优先级值转换为相同的值(例如,优先级10和9可能是

  4. 每个操作系统自行决定如何处理优先级,因为Java正在使用底层操作系统的线程机制。

  1. Priorities may have no effect at all.
  2. Priorities are only one part of a calculation that dictates scheduling.
  3. Distinct Java priority values may be translated into the same value in practice (so for example, priority 10 and 9 may be the same).
  4. Each OS makes its own decisions what to do with the priorities, as Java is using the underlying OS's threading mechanism.

请务必阅读下一篇文章,其中将向您展示如何在Linux和Windows上完成。

Be sure to read the next article after that, which shows you how it's done on Linux and Windows.

I 想想你的问题可能源于上面的第三点(如果你在Windows上运行),但可能是其他任何原因。

I think your problem may stem from the third point above (if you're running on Windows), but it may be any of the other reasons.

这篇关于通过设置优先级来执行线程执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆