interrupt 的用法??

flankingly 2006-09-28 03:10:03
对这个程序的输出的问题


package thinkInJava;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;

class Blocked extends Thread {
public synchronized void run() {
System.out.println("before wait ");
try {

wait(); // Blocks
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
System.out.println("Exiting run()");
}
}

public class Interrupt extends JApplet {
private JButton interrupt = new JButton("Interrupt");

private Blocked blocked = new Blocked();

public void init() {
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
System.out.println("aaaaaa");
remove.interrupt();
System.out.println("bbbbbbb");
}
});
blocked.start();
}

public static void main(String[] args) {
Interrupt applet = new Interrupt();
JFrame aFrame = new JFrame("Interrupt");
aFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
aFrame.add(applet, BorderLayout.CENTER);
aFrame.setSize(200, 100);
applet.init();
applet.start();
aFrame.setVisible(true);
}
} // /:~


为何是结果是:
before wait
Button pressed
aaaaaa
bbbbbbb
InterruptedException
Exiting run()
Button pressed

而 不是
before wait
Button pressed
aaaaaa
InterruptedException
Exiting run()
bbbbbbb
Button pressed

...全文
268 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
kingfish 2006-09-28
  • 打赏
  • 举报
回复
interrupt并没有立即中断一个正在运行的线程

62,616

社区成员

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

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