我刚刚用三个线程(包括主线程)制作了倒计时应用程序。 CountdownEven设置为低,以便countdownOdd将首先显示,但在输出中没有任何事情发生。任何人都可以看到问题吗?具有优先级设置的线程
//Main
public class CountdownApp
{
public static void main(String[] args)
{
new CountdownApp().start();
}
public void start()
{
Thread count1 = new CountdownEven();
Thread count2 = new CountdownOdd();
count1.setPriority(Thread.MIN_PRIORITY);
count2.setPriority(Thread.MAX_PRIORITY);
count1.start();
count2.start();
}
}
public class CountdownEven extends Thread
{
public void run()
{
for(int i = 10; i > 0; i-=2)
{
System.out.println(this.getName()+ " Count: " +i);
Thread.yield();//This is to allow the other thread to run.
}
}
}
public class CountdownOdd extends Thread
{
public void run()
{
for(int i = 9; i > 0; i-=2)
{
System.out.println(this.getName()+ " Count: " +i);
Thread.yield();//This is to allow the other thread to run.
}
}
}
设置优先级将不能保证执行顺序,尤其是在这样短的时间。 –
我刚刚运行你的代码,我得到一个输出:'线程1计数:9' /'线程1计数:7' /'线程1计数:5'等 – assylias
使用优先级不是正确的方式来定义线程的运行顺序。 – assylias