方式一:
方式二:
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();
}
}
本文通过两个Java示例展示了如何实现线程间的交替执行。第一个示例使用Runnable接口和synchronized关键字配合wait和notifyAll方法;第二个示例则通过继承Thread类并利用共享资源的notify和wait方法实现。

被折叠的 条评论
为什么被折叠?



