java中线程的优先级有什么用
答案:2 悬赏:70 手机版
解决时间 2021-02-07 21:07
- 提问者网友:做自己de王妃
- 2021-02-06 22:05
java中线程的优先级有什么用
最佳答案
- 五星知识达人网友:長槍戰八方
- 2021-02-06 23:17
要电影,又要看书,还要玩游戏。同一时间只能做一件事,但有几件事要做。这时要做最重要的。比如明天要考试了,想考好,最重要的是看书复习,然后你就看书去了。考试完了再看电影玩游戏
全部回答
- 1楼网友:纵马山川剑自提
- 2021-02-06 23:23
》》。。。而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 里)是另一个办法。
》》。。。优先级到底有什么用处?
轻易地让程序即使在非常忙碌的时候也能迅速处理使用者的输入(该输入也许是调整某项操作的优先级:)、编写游戏时更方便地实现战场上级别较高的一方优先攻击、等等。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯