方式一:
方式二:
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadEx {
private Object o = new Object(); // 共享资源
private boolean flag = true; // 互斥信号量
class Thread1 extends Thread {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:ms");
public void run() {
synchronized (o) { // 线程同步
for (int i = 1; i <= 10; i++) {
System.out.println("New thread-->A:" + sdf.format(new Date()));
o.notify(); // 唤醒另外一个进程
if(flag){
flag = false;
try {
o.wait(); // 当前线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("Thread-->A complete");
}
}
}
class Thread2 extends Thread {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:ms");
public void run() {
synchronized (o) { // 线程同步
for (int i = 1; i <= 10; i++) {
System.out.println("New thread-->B:" + sdf.format(new Date()));
o.notify(); // 唤醒另外一个进程
if(!flag){
flag = true;
try {
if(i != 10){
o.wait(); // 当前线程等待
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("Thread-->B complete");
}
}
}
public void show(){
new Thread1().start();
new Thread2().start();
}
public static void main(String[] args) {
ThreadEx t = new ThreadEx();
t.show();
}
}