java 阻塞函数_Java中实现函数的阻塞

importjavax.swing.JFrame;importjavax.swing.JButton;importjava.awt.GridLayout;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;import staticjava.lang.System.out;importjava.util.logging.Level;importjava.util.logging.Logger;public class MainFrame extendsJFrame {privateJButton blockButton, unblockButton;private final BlockTest blockTest = newBlockTest();private static final Logger LOGGER = Logger.getLogger(MainFrame.class.getName());privateMainFrame() {

initComponents();

initFrame();

}private voidinitComponents() {

blockButton= new JButton("阻塞测试");

unblockButton= new JButton("解除阻塞");

unblockButton.setEnabled(false);

blockButton.addMouseListener(newMouseAdapter() {

@Overridepublic voidmouseClicked(MouseEvent ev) {if(blockButton.isEnabled()) {//开启一个线程来完成阻塞测试,以避免阻塞应用界面而造成无法响应鼠标键盘的输入

newThread() {

@Overridepublic voidrun() {try{

blockButton.setEnabled(false);

unblockButton.setEnabled(true);

blockTest.block();//处于阻塞状态,以下finally块中的代码在阻塞被解除后才会执行

} catch(InterruptedException ex) {

LOGGER.log(Level.SEVERE,null, ex);

}finally{

out.println("mouseClicked(MouseEvent) called");

}

}

}.start();

}

}

});

unblockButton.addMouseListener(newMouseAdapter() {

@Overridepublic voidmouseClicked(MouseEvent ev) {if(unblockButton.isEnabled()) {

blockTest.unblock();

unblockButton.setEnabled(false);

blockButton.setEnabled(true);

}

}

});

setLayout(new GridLayout(2, 1));

add(blockButton);

add(unblockButton);

}private voidinitFrame() {

setTitle("block test");

setSize(300, 200);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}public static voidmain(String[] args) {

MainFrame frame= newMainFrame();

frame.setVisible(true);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值