package github.write.funding2.mapper;
/**
* @Author: MaiYu
* @Date: Create in 19:32 2020/12/12
*/
public class Main3 {
// public static void main(String[] args) {
// String s=new String();
// System.out.println("3");
// }
private static boolean flag=false;
private final static Object lock=new Object();
static class Thread1 extends Thread{
@Override
public void run() {
while (true) {
synchronized (lock) {
while (flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + "A");
flag = true;
lock.notify();
}
}
}
}
static class Thread2 extends Thread{
@Override
public void run() {
while (true) {
synchronized (lock) {
while (!flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + "B");
flag = false;
lock.notify();
}
}
}
}
public static void main(String[] args) {
new Thread1().start();
new Thread2().start();
}
}
两个线程交替打印AB
最新推荐文章于 2024-05-09 10:35:55 发布