在java中同一个线程只能被start()一次,当第二次start()就会报异常。但是我们的软件需求常常需要同一个线程多次执行同一个方法。为此可以使用notify(),wait()方法来达到我们想要的效果。先看代码
public class ThreadTest extends Thread {
private static boolean flag = false;
public ThreadTest() {
System.out.println("threadID is :"+Thread.currentThread().getId());
start();
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("main threadID is :"+Thread.currentThread().getId());
ThreadTest test = new ThreadTest();
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (test) {
test.notify();
}
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (test) {
test.notify();
flag = true;
}
}
public void threadStart() {
if (!isAlive()) {
start();
}
}
@Override
public void run() {
while(true){
try {
System.out.println("threadID is :"+Thread.currentThread().getId());
synchronized (this) {
wait();
}
if (flag) {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
我的做法是让子线程循环执行前等待主线程的通知,当主线程发出通知后子线程才能继续循环执行,每一次执行都需要等待,当然如果想结束子线程直接跳出循环就可以。
以上思路代码均为自己的理解,如有错误之处敬请各位大神予以斧正。