当前位置:   article > 正文

Java线程的暂停与恢复_java线程暂停和恢复

java线程暂停和恢复

 Java以前的suspend和resume方法过时不建议使用。

那怎么办呢?

具体说起来比较复杂,需要暂停标志加synchronized+等待/唤醒

详见代码

 

  1. package defaul;
  2. import java.awt.BorderLayout;
  3. import java.awt.Font;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import java.util.Random;
  7. import javax.swing.JButton;
  8. import javax.swing.JFrame;
  9. import javax.swing.JLabel;
  10. import javax.swing.SwingConstants;
  11. public class ThreadSuspendframe extends JFrame{
  12. private JLabel label;//显示数字中的标签
  13. String[] numb = {"15180691681","13870225947","13870261079","12345671111","1397995240"};
  14. public ThreadSuspendframe(){
  15. setTitle("手机号抽奖");
  16. setBounds(200, 200, 400, 400);
  17. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  18. MyThread myThread = new MyThread();
  19. label = new JLabel("0");//实例化标签 初始化为0
  20. myThread.start();
  21. label.setHorizontalAlignment(SwingConstants.CENTER);//设置文字居中
  22. label.setFont(new Font("宋体", Font.BOLD, 42));//设置字体
  23. getContentPane().add(label, BorderLayout.CENTER);
  24. JButton jButton = new JButton("暂停");
  25. jButton.addActionListener(new ActionListener() {
  26. @Override
  27. public void actionPerformed(ActionEvent e) {
  28. String Btn = jButton.getText();
  29. if(Btn.equals("暂停"))
  30. {
  31. myThread.toSuspend();
  32. jButton.setText("继续");
  33. }else{
  34. myThread.toResume();
  35. jButton.setText("暂停");
  36. }
  37. }
  38. });
  39. getContentPane().add(jButton, BorderLayout.SOUTH);
  40. setVisible(true);
  41. }
  42. class MyThread extends Thread{
  43. private boolean suspend = false;
  44. public synchronized void toSuspend(){
  45. suspend = true;
  46. }
  47. public synchronized void toResume(){
  48. notify();//当前等待的线程继续执行
  49. suspend = false;
  50. }
  51. @Override
  52. public void run() {
  53. // TODO Auto-generated method stub
  54. while(true){
  55. synchronized (this) {
  56. while(suspend){
  57. try {
  58. wait();//让线程进入等待状态
  59. } catch (InterruptedException e) {
  60. // TODO Auto-generated catch block
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65. int randomNum = new Random().nextInt(numb.length);//获取数组随机索引
  66. String phone = numb[randomNum];
  67. label.setText(phone);
  68. }
  69. }
  70. }
  71. public static void main(String[] args) {
  72. new ThreadSuspendframe();
  73. }
  74. }

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号