java 优先级意思_java线程优先级有什么意义?

匿名用户

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 里)是另一个办法。

》》。。。优先级到底有什么用处?

轻易地让程序即使在非常忙碌的时候也能迅速处理使用者的输入(该输入也许是调整某项操作的优先级:)、编写游戏时更方便地实现战场上级别较高的一方优先攻击、等等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值