import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by jack on 2018/1/18.
*/
public class PrintAbc {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();
Condition c3 = lock.newCondition();
ThreadGroup group = new ThreadGroup("test");
new Thread(group, new Print1(1, lock, c1, c2)).start();
new Thread(group, new Print1(2, lock, c2, c3)).start();
new Thread(group, new Print1(3, lock, c3, c1)).start();
Thread.yield();
}
}
class Print1 implements Runnable {
public static volatile AtomicInteger printNumber = new AtomicInteger(1);
private int threadId = 0;
Condition current, next;
ReentrantLock lock;
public Print1(int threadId, ReentrantLock lock, Condition current, Condition next) {
this.threadId = threadId;
this.current = current;
this.next = next;
this.lock = lock;
}
@Override
public void run() {
while (printNumber.get() < 75) {
lock.lock();
for (int i = 0; i < 5; i++) {
System.out.println("线程" + threadId + ":" + printNumber.getAndIncrement());
}
next.signalAll();
try {
current.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public class PrintThree {
public static void main(String[] args) {
Object lockA = new Object();
Object lockB = new Object();
Object lockC = new Object();
ThreadGroup aa = new ThreadGroup("test");
new Thread(aa, new PrintRunable(1, lockC, lockA)).start();
new Thread(aa, new PrintRunable(2, lockA, lockB)).start();
new Thread(aa, new PrintRunable(3, lockB, lockC)).start();
System.out.println("ed");
}
}
class PrintRunable implements Runnable {
public static volatile int printNum = 1;
private int threadId = 0;
Object prev = null;
Object current = null;
public PrintRunable(int threadId) {
this.threadId = threadId;
}
public PrintRunable(int threadId, Object prev, Object current) {
this.threadId = threadId;
this.current = current;
this.prev = prev;
}
@Override
public synchronized void run() {
while (true) {
while (printNum < 75) {
synchronized (current) {
for (int i = 0; i < 5; i++) {
System.out.println("线程" + threadId + ":" + printNum++);
}
current.notifyAll();
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
线程1:1
线程1:2
线程1:3
线程1:4
线程1:5
线程2:6
线程2:7
线程2:8
线程2:9
线程2:10
线程3:11
线程3:12
线程3:13
线程3:14
线程3:15
线程1:16
线程1:17
线程1:18
线程1:19
线程1:20
线程2:21
线程2:22
线程2:23
线程2:24
线程2:25
线程3:26
线程3:27
线程3:28
线程3:29
线程3:30
线程1:31
线程1:32
线程1:33
线程1:34
线程1:35
线程2:36
线程2:37
线程2:38
线程2:39
线程2:40
线程3:41
线程3:42
线程3:43
线程3:44
线程3:45
线程1:46
线程1:47
线程1:48
线程1:49
线程1:50
线程2:51
线程2:52
线程2:53
线程2:54
线程2:55
线程3:56
线程3:57
线程3:58
线程3:59
线程3:60
线程1:61
线程1:62
线程1:63
线程1:64
线程1:65
线程2:66
线程2:67
线程2:68
线程2:69
线程2:70
线程3:71
线程3:72
线程3:73
线程3:74
线程3:75