package test.thread;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SYNThread {
boolean source = false;
public synchronized void printA(){
while(source){
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("A:"+new SimpleDateFormat("yyyy年mm月dd日 hh:mm:ss").format(new Date()));
source = true;
notify();
}
public synchronized void printB(){
while(!source){
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("B:"+new SimpleDateFormat("yyyy年mm月dd日 hh:mm:ss").format(new Date()));
source = false;
notify();
}
static class ThreadA extends Thread{
SYNThread syn = null;
public ThreadA(SYNThread syn){
this.syn = syn;
}
public void run(){
for(int i = 0;i<10;i++){
syn.printA();
try {
sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
static class ThreadB extends Thread{
SYNThread syn = null;
public ThreadB(SYNThread syn){
this.syn = syn;
}
public void run(){
for(int i = 0;i<10;i++){
syn.printB();
try {
sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
public static void main(String[] args) {
SYNThread synt = new SYNThread();
Thread a = new ThreadA(synt);
Thread b = new ThreadB(synt);
a.start();
b.start();
}
}
java 线程 交替输出
最新推荐文章于 2022-09-13 15:14:43 发布