MainTest类中可以控制线程的暂停或继续运行。
public class MainTest {
/**
* 这个线程操作另一个线程的暂停或开始
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread1 th1 = new Thread1();
Thread t1 = new Thread(th1);
t1.start();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//thread线程暂停
th1.wait1();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//thread线程继续运行
th1.start1();
//th1.wait1();
//th1.start1();
}
}
下面是thread类
public class Thread1 implements Runnable {
private String flag = "start";
private String control = "";
public void run() {
// TODO Auto-generated method stub
int i = 0;
while (true) {
if (flag.equals("start")) {
i++;
System.out.println("The thread1 is running" + i);
} else if (flag.equals("wait")) {
try {
System.out.println("===wait===");
synchronized (control) {
control.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void wait1() {
this.flag = "wait";
}
public void start1() {
this.flag = "start";
if (flag.equals("start")) {
synchronized (control) {
control.notifyAll();
}
}
}
}
定义了一个标志位。还利用了synchronized同步关键字