线程sleep和优先级的问题

bnupan 2009-10-11 09:39:21
刚刚自学线程部分,有点模模糊糊的,编写了一些代码,没有如预期执行,请各位高手指点。
下面是代码:

import java.lang.*;
class Test extends Thread{
int flag;
public Test(int x){
this.flag=x;
}
public static void main(String argv[]){
Test t = new Test(1);
Test s = new Test(2);
t.setPriority(1);
s.setPriority(MAX_PRIORITY);
t.start();
System.out.println("one");
s.start();
System.out.println("two");
}
public void run(){
for(int i=0;i<3;i++){
if(flag==1){
System.out.println("Thread t");
}
else{
System.out.println("Thread s");
}
try{
Thread.sleep(3000);
Thread.interrupted();
}catch(InterruptedException e){

if(flag==1)System.out.println("t sleep");
else if(flag==2)System.out.println("s sleep");

}
}
}

运行时,线程t和s确实都sleep了,但catch程序块中的代码始终未执行,不知道是什么原因呢?
另,通过t.setPriority(1);s.setPriority(MAX_PRIORITY);设置优先级后,由于s的优先级高于t,一定是s进程先被执行么~
谢谢各位!
...全文
170 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
bnupan 2009-10-12
  • 打赏
  • 举报
回复
谢谢各位!
是不是一个线程sleep时,可能会被别的线程打断也可能不会,线程不被打断的时候就不会有InterruptedException呢?是不是某个线程比正在休眠的线程优先级高,就会打断休眠的线程呢?
之前看到一本书上写的sleep函数必将导致InterruptedException,所以必须catch,可能是对这句话理解错误了。
zenghuiss 2009-10-12
  • 打赏
  • 举报
回复
当线程sleep后被打断会抛InterruptedException
lz对异常的概念不是很清楚 再看看相关资料吧
loveofmylife 2009-10-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 panpan_bnu 的回复:]
谢谢各位!

之前看到一本书上写的sleep函数必将导致InterruptedException,所以必须catch,可能是对这句话理解错误了。
[/Quote]
sleep,wait,等阻塞操作是可以Interrupted的,会抛出一个InterruptedException异常
而被锁互斥的阻塞和I/o流的阻塞(除了管道流以外)都是不可被Interrupted的
阿_布 2009-10-11
  • 打赏
  • 举报
回复

class TestThreadPriority extends Thread {
int flag;
TestThreadPriority ttp;

public TestThreadPriority(int x) {
this.flag = x;
}

public TestThreadPriority(int x, TestThreadPriority ttp) {
this.flag = x;
this.ttp = ttp;
}

public static void main(String argv[]) {
TestThreadPriority s = new TestThreadPriority(2);
TestThreadPriority t = new TestThreadPriority(1, s);
t.setPriority(1);
s.setPriority(MAX_PRIORITY);
t.start();
System.out.println("one");
s.start();
System.out.println("two");
}

public void run() {
for (int i = 0; i < 3; i++) {
if (flag == 1) {
System.out.println("Thread t");
try {
ttp.interrupt();
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("t sleep");
}
} else {
System.out.println("Thread s");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("s sleep");
}
}
}
}
}
loveofmylife 2009-10-11
  • 打赏
  • 举报
回复
Thread.interrupted(); 换成interrupt();
应该是先执行高优先级的在执行低优先级的
swandragon 2009-10-11
  • 打赏
  • 举报
回复
public static boolean interrupted() 测试当前线程是否已经中断

睡眠没有被打断所以catch不执行

这样就能看到结果了

public static void main(String argv[]){
Test t = new Test(1);
Test s = new Test(2);
t.setPriority(1);
s.setPriority(MAX_PRIORITY);
t.start();
System.out.println("one");
s.start();
//public void interrupt() 中断线程。
t.interrupt();
System.out.println("two");
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧