两个线程交替打印1-100
1:通过synchronized 和 wait(), notify() 进行交替打印
package com.jTest.leet;
public class AlternatelyPrint {
private static final Object lock = new Object(); //表示对象锁
private static volatile int index = 1;
private static volatile boolean flag = false;
class A implements Runnable {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
synchronized (lock){
while (flag){
try {
//等待过程中,会把锁让出来,这样其它线程就可以进入
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A:"+index);
index++;
flag = true;
lock.notify();
}
}
}
}
class B implements Runnable {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
synchronized (lock){
while (!flag){
try {
//等待过程中,会把锁让出来,这样其它线程就可以进入
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B:"+index);
index++;
flag = false;
lock.notify();
}
}
}
}
public static void main(String[] args) {
AlternatelyPrint solution2 = new AlternatelyPrint();
Thread threadA = new Thread(solution2.new A());
Thread threadB = new Thread(solution2.new B());
threadA.start();
threadB.start();
}
}
参考链接:https://www.cnblogs.com/liwangcai/p/10741644.html