线程暂停继续


import javax.swing.*;

import java.awt.*;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

/**

* https://blog.csdn.net/kimimoko/article/details/84860378

* */

public class Main {

private static MyThread myThread;
//标记
    private static boolean onAction =false;

    public static void main(String[] args) {

        JFrame jFrame =new JFrame("妈蛋");

        jFrame.setBounds(500, 500, 50, 100);

        jFrame.setLayout(new FlowLayout());

        JButton jButton =new JButton("开始");

        jButton.addMouseListener(new MouseAdapter() {

           @Override
            public void mouseClicked(MouseEvent e) {
                if (myThread ==null) {
                    myThread =new MyThread();
                    new Thread(myThread).start();
                    onAction =true;
                    jButton.setText("暂停");
                }else if (myThread !=null &&onAction ==true) {
                 onAction =false;
                  jButton.setText("继续");
                  myThread.pauseThread();
                }else {
myThread.resumeThread();
                    onAction =true;
                    jButton.setText("暂停");
                }
}
});
        jFrame.add(jButton);
        jFrame.setVisible(true);
    }
}
class MyThread extends Thread {
private boolean pause =false;
    void pauseThread() {
        pause =true;
    }

void resumeThread() {
pause =false;
        synchronized (this) {
this.notify();
        }
}
@Override
    public void run() {
for (int i =0; i <100; i++) {
while (pause) {
synchronized (this) {
try {
this.wait();
                    }catch (InterruptedException e) {
e.printStackTrace();
                    }
}
}
try {
Thread.sleep(500);
            }catch (InterruptedException e) {
e.printStackTrace();
            }
System.out.println(i);
        }
}

}

你可能感兴趣的:(线程暂停继续)