package thread;class ThreadA extends Thread {
boolean threadFlag=true;
int click;
ThreadA(String threadName) {
super(threadName);
start();
}
public void run() {
while(threadFlag)
click++;
}
public void cancel() {
threadFlag=false;
}
}
public class ThreadWithPriority {
public static void main(String[] args) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
ThreadA t01=new ThreadA("Thread01");
ThreadA t02=new ThreadA("Thread02");
ThreadA t03=new ThreadA("Thread03");
// t01:6 t02:5 t03:4
t01.setPriority(Thread.NORM_PRIORITY+1);
t03.setPriority(Thread.NORM_PRIORITY-1);
try {
Thread.sleep(10000);
}
catch(InterruptedException e) { System.out.println("Main interrupt."); }
t01.cancel();
t02.cancel();
t03.cancel();
try {
t01.join();
t02.join();
t03.join();
}
catch(Exception e) { System.out.println("Thread Interrupt."); }
System.out.println(t01.getName()+":"+t01.click);
System.out.println(t02.getName()+":"+t02.click);
System.out.println(t03.getName()+":"+t03.click);
}
}运行结果:
C:\classes\thread>java thread.ThreadWithPriority
Thread01:13994
Thread02:1228687562
Thread03:52494048为什么结果是 t02>t03>>t01?
boolean threadFlag=true;
int click;
ThreadA(String threadName) {
super(threadName);
start();
}
public void run() {
while(threadFlag)
click++;
}
public void cancel() {
threadFlag=false;
}
}
public class ThreadWithPriority {
public static void main(String[] args) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
ThreadA t01=new ThreadA("Thread01");
ThreadA t02=new ThreadA("Thread02");
ThreadA t03=new ThreadA("Thread03");
// t01:6 t02:5 t03:4
t01.setPriority(Thread.NORM_PRIORITY+1);
t03.setPriority(Thread.NORM_PRIORITY-1);
try {
Thread.sleep(10000);
}
catch(InterruptedException e) { System.out.println("Main interrupt."); }
t01.cancel();
t02.cancel();
t03.cancel();
try {
t01.join();
t02.join();
t03.join();
}
catch(Exception e) { System.out.println("Thread Interrupt."); }
System.out.println(t01.getName()+":"+t01.click);
System.out.println(t02.getName()+":"+t02.click);
System.out.println(t03.getName()+":"+t03.click);
}
}运行结果:
C:\classes\thread>java thread.ThreadWithPriority
Thread01:13994
Thread02:1228687562
Thread03:52494048为什么结果是 t02>t03>>t01?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货