请问Thread 中interrupt 的用法是什么,有什么作用和效果?谢谢

lovesummer 2003-11-27 10:13:42
如题
...全文
183 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lzy9819 2003-11-27
  • 打赏
  • 举报
回复
使用Thread的interrupt()来中断被停滞的程序代码
lzy9819 2003-11-27
  • 打赏
  • 举报
回复
//: 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);
}
} ///:~
lovesummer 2003-11-27
  • 打赏
  • 举报
回复
下面的程序是否应该在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);

}
}

62,614

社区成员

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

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