如何停止线程,你目前的考虑是明显有问题的。我做了如下的改动,你看看。 /** * @author hall * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class MyThread extends Thread { boolean running; public MyThread(){ super(); running = true; } public void run(){ while (running){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("AAA"); } System.out.println("BBB"); }
void stopMe(){ running = false; }
void resumeMe() { running = true; } public static void main(String[] args) { int i=1; try{ MyThread mythread=new MyThread(); mythread.start(); while (i<8){ Thread.sleep(1000); System.out.print(i + " "); System.out.println(mythread.running); if (i==5) { mythread.stopMe(); } if (!mythread.isAlive()) { System.out.println("thread will continue after 3 seconds!"); Thread.sleep(3000); mythread.resumeMe(); mythread.run(); } System.out.print("\n"); i=i+1; } } catch(Exception e){ System.out.println(e.toString()); } } }
{if(thread==null){thread=new Thread(this);thread.start();}}
sychronized(this) { this.wait();};
/**
* @author hall
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class MyThread extends Thread {
boolean running;
public MyThread(){
super();
running = true;
}
public void run(){
while (running){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("AAA");
}
System.out.println("BBB");
}
void stopMe(){
running = false;
}
void resumeMe() {
running = true;
}
public static void main(String[] args) {
int i=1;
try{
MyThread mythread=new MyThread();
mythread.start();
while (i<8){
Thread.sleep(1000);
System.out.print(i + " ");
System.out.println(mythread.running);
if (i==5) {
mythread.stopMe();
}
if (!mythread.isAlive()) {
System.out.println("thread will continue after 3 seconds!");
Thread.sleep(3000);
mythread.resumeMe();
mythread.run();
}
System.out.print("\n");
i=i+1;
}
}
catch(Exception e){
System.out.println(e.toString());
}
}
}