下面的程序是否应该在join 的时候产生异常?
interrupt是不是跟一个线程的开关一样?运行一次暂停线程,再运行一次有让线程继续运行?
我得理解不知道对不对,但是下面的程序好像运行起来结果不像我想象的那样。public class join3 {
    public static void main(String args[]) {
        HelloRunner r = new HelloRunner();
        Thread t = new Thread(r, "hellothread");        if (null != t) {
            System.out.println("thread create.");
        } else {
            System.out.println("thread create error!");
        }        ThreadA t1 = new ThreadA(t);        t.start();
        t1.start();        try{
            Thread.sleep(10);
        }catch(InterruptedException m){}        try{
            t.join();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException!");
        }        System.out.println("thread is " + (t.isAlive()?"alive": "not alive"));
    }
}class ThreadA extends Thread{    private Thread thdOther;    ThreadA(Thread thdOther){
        this.thdOther = thdOther;
    }    public void run(){        System.out.println("interrupt t");        while(true)
            thdOther.interrupt();
    }
}class HelloRunner implements Runnable {    public void run() {
        System.out.println("t running");        while(true);    }
}

解决方案 »

  1.   

    //: c14:Interrupt.java
    // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
    // www.BruceEckel.com. See copyright notice in CopyRight.txt.
    // The alternative approach to using 
    // stop() when a thread is blocked.
    // <applet code=Interrupt width=200 height=100>
    // </applet>
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import com.bruceeckel.swing.*;class Blocked extends Thread {
      public synchronized void run() {
        try {
          wait(); // Blocks
        } catch(InterruptedException e) {
          System.err.println("Interrupted");
        }
        System.out.println("Exiting run()");
      }
    }public class Interrupt extends JApplet {
      private JButton 
        interrupt = new JButton("Interrupt");
      private Blocked blocked = new Blocked();
      public void init() {
        Container cp = getContentPane();
        cp.setLayout(new FlowLayout());
        cp.add(interrupt);
        interrupt.addActionListener(
          new ActionListener() {
            public 
            void actionPerformed(ActionEvent e) {
              System.out.println("Button pressed");
              if(blocked == null) return;
              Thread remove = blocked;
              blocked = null; // to release it
              remove.interrupt();
            }
          });
        blocked.start();
      }
      public static void main(String[] args) {
        Console.run(new Interrupt(), 200, 100);
      }
    } ///:~
      

  2.   

    使用Thread的interrupt()来中断被停滞的程序代码