刚刚自学线程部分,有点模模糊糊的,编写了一些代码,没有如预期执行,请各位高手指点。
下面是代码: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进程先被执行么~
谢谢各位!

解决方案 »

  1.   

    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");
    }
      

  2.   

    Thread.interrupted();  换成interrupt();
    应该是先执行高优先级的在执行低优先级的
      

  3.   


    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");
    }
    }
    }
    }
    }
      

  4.   

    谢谢各位!
    是不是一个线程sleep时,可能会被别的线程打断也可能不会,线程不被打断的时候就不会有InterruptedException呢?是不是某个线程比正在休眠的线程优先级高,就会打断休眠的线程呢?
    之前看到一本书上写的sleep函数必将导致InterruptedException,所以必须catch,可能是对这句话理解错误了。
      

  5.   

    sleep,wait,等阻塞操作是可以Interrupted的,会抛出一个InterruptedException异常
    而被锁互斥的阻塞和I/o流的阻塞(除了管道流以外)都是不可被Interrupted的
      

  6.   

    当线程sleep后被打断会抛InterruptedException
    lz对异常的概念不是很清楚  再看看相关资料吧