方法一:传统wait/notifyAll+等待标记mark
static AtomicInteger i = new AtomicInteger(1);
static Object lock = new Object();
static int mark = 1;
Thread a = new Thread(() -> {
while (i.get() < 100){
synchronized (lock){
while (mark != 1){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程a:" + i.getAndIncrement());
lock.notifyAll();
mark = 2;
}
}
});
Thread b = new Thread(() -> {
while (i.get() <= 100){
synchronized (lock){
while (mark != 2){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程b:"+i.getAndIncrement());
lock.notifyAll();
mark = 1;
}
}
});
a.start();
b.start();
方法二:信号量Semaphore
static AtomicInteger i = new AtomicInteger(1);
static Semaphore s1 = new Semaphore(1);
static Semaphore s2 = new Semaphore(0);
Thread a = new Thread(() -> {
try {
while(i.get() < 100){
s1.acquire();
System.out.println("线程-a:" + i.getAndIncrement());
s2.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread b = new Thread(() -> {
try {
while(i.get() < 100){
s2.acquire();
System.out.println("线程-b:" + i.getAndIncrement());
s1.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
a.start();
b.start();
方法三:LockSupport
static AtomicInteger i = new AtomicInteger(1);
Thread [] threads = new Thread[2];
threads[0] = new Thread(() -> {
while (i.get() < 100){
System.out.println("线程a:" + i.getAndIncrement());
LockSupport.unpark(threads[1]);
LockSupport.park();
}
});
threads[1] = new Thread(() -> {
while (i.get() < 100){
LockSupport.park();
System.out.println("线程b:" + i.getAndIncrement());
LockSupport.unpark(threads[0]);
}
});
threads[0].start();
threads[1].start();