匿名用户
1级
2007-09-04 回答
》》。。。而sleep之后就会随机排序了,优先级此时就不起作用了,有没有解决的办法?
其中一个办法是让每一个线程记得必须比它先完成的另一个线程,
然后在必要时强制它放弃执行一直到那另一个线程执行完为止。 比如:
class CustomThread extends Thread {
private Thread 先完;
CustomThread(String name, Thread 先完) {
super(name);
this.先完 = 先完;
}
public void run() {
System.out.println(this.getName());
try {
sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (先完 != null)
try {
先完.join();
} catch (InterruptedException e) {}
System.out.println("NAME: " + this.getName() + " Bye");
}
}
class MultiThread {
public static void main(String args[]) throws InterruptedException {
CustomThread thread1 = new CustomThread("first", null);
CustomThread thread2 = new CustomThread("second", thread1);
CustomThread thread3 = new CustomThread("third", thread2);
CustomThread thread4 = new CustomThread("fourth", thread3);
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY-1);
thread3.setPriority(Thread.MAX_PRIORITY-2);
thread4.setPriority(Thread.MAX_PRIORITY-3);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
4 等 3、3 等 2、。。。 串联成单一线程了,所以如果情况允许的话,
把所有必须顺序执行的任务集合在单一线程里(比如留在 main 里)是另一个办法。
》》。。。优先级到底有什么用处?
轻易地让程序即使在非常忙碌的时候也能迅速处理使用者的输入(该输入也许是调整某项操作的优先级:)、编写游戏时更方便地实现战场上级别较高的一方优先攻击、等等。