经常被问 多个线程如何交替打印?
下面来两种方式
Rentrantlock 的 condition
class ShareResource {
private int number = 1;// 控制线程谁开始运行
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
public void print1(){
lock.lock();
while(number != 1){
try {
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number = 2;
System.out.println("线程1打印");
c2.signal();
lock.unlock();
}
public void print2(){
lock.lock();
while(number != 2){
try {
c2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number = 3;
System.out.println("线程2打印");
c3.signal();
lock.unlock();
}
public void print3(){
lock.lock();
while(number != 3){
try {
c3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number = 1;
System.out.println("线程3打印");
c1.signal();
lock.unlock();
}
}
public class SyncReentrantLockTest {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(()->{
for (int i = 0; i < 10 ; i++) {
shareResource.print1();
}
}).start();
new Thread(()->{
for (int i = 0; i < 10 ; i++) {
shareResource.print2();
}
}).start();
new Thread(()->{
for (int i = 0; i < 10 ; i++) {
shareResource.print3();
}
}).start();
}
}
结果
线程1打印
线程2打印
线程3打印
线程1打印
线程2打印
线程3打印
Semaphore
public class SemaphoreTest {
private Semaphore t1 = new Semaphore(1);
private Semaphore t2 = new Semaphore(0);
private void print1(){
try {
t1.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1打印");
t2.release();
}
private void print2(){
try {
t2.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2打印");
t1.release();
}
public static void main(String[] args) {
SemaphoreTest semaphoreTest = new SemaphoreTest();
new Thread(()->{
for (int i = 0; i < 2 ; i++) {
semaphoreTest.print1();
}
}).start();
new Thread(()->{
for (int i = 0; i < 2 ; i++) {
semaphoreTest.print2();
}
}).start();
}
}
结果
线程1打印
线程2打印
线程1打印
线程2打印