源代码
class MyThread implements Runnable{
private boolean flag = true;
public void run() {
int i = 0;
while(this.flag) {
System.out.println(Thread.currentThread().getName() + "i = " + (i ++));
}
}
public void stop(){
this.flag = false;
}
}
public class ThreadStopDemo01{
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread t = new Thread(mt,"线程");
t.start();
try {
Thread.sleep(30);
}catch(Exception e) {
e.printStackTrace();
}
t.stop();
}
}
报错类型为
后来发现可能是方法的引用错了,stop()方法是MyThread类里面的,然后更改了一下代码(t.stop---->mt.stop)就好了
class MyThread implements Runnable{
private boolean flag = true;
public void run() {
int i = 0;
while(this.flag) {
System.out.println(Thread.currentThread().getName() + "i = " + (i ++));
}
}
public void stop(){
this.flag = false;
}
}
public class ThreadStopDemo01{
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread t = new Thread(mt,"线程");
t.start();
try {
Thread.sleep(30);
}catch(Exception e) {
e.printStackTrace();
}
mt.stop();
}
}
百度了半天没有个所以然,关键时刻还是要靠自己