package 线程;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestThread extends JFrame {
/**
*
*/
//private static final long serialVersionUID = 1L;
JPanel jPanel1 = new JPanel();
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
MyThread thread = null;
private boolean isContinue;
public TestThread() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startButton_actionPerformed(e);
}
});
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
stopButton_actionPerformed(e);
}
});
Container con=getContentPane();
con.add(jPanel1, BorderLayout.CENTER);
jPanel1.add(startButton);
startButton.setBounds(36, 105, 82, 30);
jPanel1.add(stopButton);
stopButton.setBounds(160, 108, 100, 31);
}
void startButton_actionPerformed(ActionEvent e) {
if (thread != null)//这是啥意思?
isContinue=false;
thread = new MyThread();//为什么我改为MyThread thread=new MyThread();运行会报错?
thread.start();
}
void stopButton_actionPerformed(ActionEvent e) {
if (thread != null)
isContinue=false;
thread = null;//这又是啥意思?
}
public static void main(String[] args) {
TestThread test = new TestThread();
test.setBounds(300,300,300, 80);
test.setVisible(true);
}
private class MyThread extends Thread {
public MyThread() {
//isContinue=true;//为什么不在意开头哪里就定义iscontinue=true?
}
public void run() {
System.out.println("\n\n");
while (true && isContinue) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Java 编程词典\thttp://www.mrbccd.com");
}
}
}
}
if (thread != null)//这是啥意思? 如果线程不为空
thread = new MyThread();//为什么我改为MyThread thread=new MyThread();运行会报错?
上面已经定义我thread ,现在定义thread ,生命周期是在当前函数里面。出了函数就没有了,所以会运行错误 。
thread = null;//这又是啥意思?
线程为空
/isContinue=true;//为什么不在意开头哪里就定义iscontinue=true?
这个看不懂你说的意思?
回答你那个再次定义MyThread的错误,因为你已经定义了一个成员变量是这个名字,所以再次定义就会报错,然后其他的错误是判断线程存在与否,不存在时申请,存在时不申请,释放的时候相反就可以了!
我觉得你有很多东西不是很清楚。。。
首先,像thread,isContinue这样的成员变量,在一个方法中被改变,对所有方法生效。大家看到或用到的是同一个东西。
其次,你要明白,你点按钮所做的事情和MyThread#run所做的事情是并行的,没有先后顺序(除了第一次启动MyThread#run)。
并且,这两个并行的事情之间需要交互,就有了isContinue。
还有,这是桌面程序,你程序的入口有多个(多个按钮),虽然一次只能进入一个方法(入口),但是它们的运行没有先后顺序。谁先运行,谁后运行,谁又再次运行,完全取决于画面操作者。程序角度无法确定。除非你加个标识变量,来告诉别的方法(入口),我已经做过什么了。
知道了这些,你自己再想想吧,自己想明白的东西才是真明白。
ps:我觉得这个程序对你来说太难。
thread = new MyThread();//为什么我改为MyThread thread=new MyThread();运行会报错?原因: 全局变量已经声明了一个:MyThread thread = null;你再声明自然就重复定义了
private boolean isContinue; 存储状态的变量,应该是根据情况需要来对其赋予不同的状态,后续操作以此做出判断依据
thread = null;//这又是啥意思? 我浅显的理解:停止不需要的线程
加油,慢慢看懂,不懂度娘,争取弄懂。
ps:我觉得这个程序对你来说太难。