有两个按钮,一个“暂停”,一个是“开始执行”。java如何让程序暂停、执行。
当点击“暂停”时程序暂停,当点击“开始执行”时,程序暂停后执行。如何实现?
------解决方案--------------------多线程解决,具体的我也不太熟
------解决方案--------------------一个暂停线程,一个唤醒线程就可以了
------解决方案--------------------我的写法:
package org.battwofame.hellojava.test.test1;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame extends JFrame {
private MyThread mt = new MyThread();
{
Thread t = new Thread(mt);
t.start();
}
public void createFrame() {
JPanel jp = new JPanel(new FlowLayout());
this.add(jp);
JButton jbStart = new JButton( "开始 ");
JButton jbEnd = new JButton( "暂停 ");
jp.add(jbStart);
jp.add(jbEnd);
this.setSize(300, 100);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mt.setBa(true);
}
});
jbEnd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mt.setBa(false);
}
});
}
public static void main(String[] args) {
MyFrame mf = new MyFrame();
mf.createFrame();
}
}
class MyThread implements Runnable {
private boolean ba = false;
public void run() {
int i = 0;
while(true) {
if(ba) {
System.out.println(i ++ );
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public boolean isBa() {
return ba;
}
public void setBa(boolean ba) {
this.ba = ba;
}
}
如果你是在页面上控制的话,原理是一样的~~~,自己动动脑再想看~~~