package com.company.lyh;
import com.sun.corba.se.spi.copyobject.CopyobjectDefaults;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static Lock lock = new ReentrantLock();
private static int count = 0;
private static Semaphore A = new Semaphore(1);
private static Semaphore B = new Semaphore(1);
private static Semaphore C = new Semaphore(1);
public static void main(String[] args){
// write your code here
final Main demo2 = new Main();
Thread t1 = new Thread(demo2::print1);
Thread t2 = new Thread(demo2::print2);
Thread t3 = new Thread(demo2::print3);
try {
B.acquire();
C.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.start();
t2.start();
t3.start();
}
public void print1() {
for (int i = 0; i <= 100; i += 3) {
try {
A.acquire();
if((i+3)%3==0)
{
System.out.println("print1:"+i);
}
B.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void print2() {
for (int i = 1; i <= 100; i += 3) {
try {
B.acquire();
if((i+3)%3==1)
{
System.out.println("print2:"+i);
}
C.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void print3() {
for (int i = 2; i <= 100; i += 3) {
try {
C.acquire();
if((i+3)%3==2)
{
System.out.println("print3:"+i);
}
A.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
输出结果如下:
print1:0
print2:1
print3:2
print1:3
print2:4
print3:5
print1:6
print2:7
print3:8
print1:9
print2:10
print3:11
print1:12
print2:13
print3:14
print1:15
print2:16
print3:17
print1:18
print2:19
print3:20
print1:21
print2:22
print3:23
print1:24
print2:25
print3:26
print1:27
print2:28
print3:29
print1:30
print2:31
print3:32
print1:33
print2:34
print3:35
print1:36
print2:37
print3:38
print1:39
print2:40
print3:41
print1:42
print2:43
print3:44
print1:45
print2:46
print3:47
print1:48
print2:49
print3:50
print1:51
print2:52
print3:53
print1:54
print2:55
print3:56