通知等待
如果让打印ABC 那就把flag换成一个num,用来区分。
package sync;
public class PrintAB {
static boolean flag = true;
private static final Object foo= new Object(); // 锁标志
static class A implements Runnable{
@Override
public void run() {
for (int i = 0; i < 4; i++) {
synchronized (foo){
try {
while(!flag){
foo.wait();
}
System.out.println('A');
flag = false;
foo.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class B implements Runnable{
@Override
public void run() {
for (int i = 0; i < 4; i++) {
synchronized (foo){
try {
while(flag){
foo.wait();
}
System.out.println('B');
flag = true;
foo.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread A = new Thread(new A());
Thread B = new Thread(new B());
A.start();
B.start();
}
}
信号量
package demo;
import java.util.concurrent.Semaphore;
public class Test {
static Semaphore A = new Semaphore(1);
static Semaphore B = new Semaphore(0);
static class A implements Runnable{
@Override
public void run() {
for (int i = 0; i < 4; i++) {
try {
A.acquire();
System.out.println('A');
B.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class B implements Runnable{
@Override
public void run() {
for (int i = 0; i < 4; i++) {
try {
B.acquire();
System.out.println('N');
A.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread A = new Thread(new A());
Thread B = new Thread(new B());
A.start();
}
}