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
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者