package ThreadTest.ABC;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
case1:使用LockAndCondition
*/
public class ThreadPrintABCWithLockAndCondition {
private static volatile int count = 0;//利用count值来判定条件是否成立
private static Lock lock = new ReentrantLock();//实现互斥
private static Condition A = lock.newCondition();//三个信号量,用于实现三个线程之间的同步
private static Condition B = lock.newCondition();
private static Condition C = lock.newCondition();
private static class ThreadA extends Thread{
@Override
public void run() {
try {
lock.lock();
for(int i=0;i<10;i++){
while (count % 3 != 0) {
A.await();
}
System.out.print("A");
count++;
B.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
private static class ThreadB extends Thread{
@Override
public void run() {
try {
lock.lock();
for(int i=0;i<10;i++){
while (count % 3 != 1) {
B.await();
}
System.out.print("B");
count++;
C.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
private static class ThreadC extends Thread{
@Override
public void run() {
try {
lock.lock();
for(int i=0;i<10;i++){
while (count % 3 != 2) {
C.await();
}
System.out.print("C");
count++;
A.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}
package ThreadTest.ABC;
public class ThreadPrintABCWithSyn {
/*
* case2:使用synchronized
* */
private static class ThreadPrinter implements Runnable{
private String name;
private Object pre;
private Object cur;
private ThreadPrinter(String name,Object pre,Object cur){
this.name = name;
this.pre = pre;
this.cur = cur;
}
@Override
public void run() {
int count = 1;
while(count<=10){//用while而不是if的原因是防止虚假唤醒,而且先进行while循环而不是先去syn的原因是如果当前打印次数已经够了(>=10)了,此时根本不用再去进行加解锁了(因为加解锁同样也会有开销)。
synchronized (pre){//保证前面一个打印任务已经完成
synchronized (cur){
System.out.print(name);
count++;
cur.notifyAll();
}
try {
if(count==11){//这一步是用于当count==10后也就是进行完最后一次打印后,
// 由于无法再次进行循环体所以此时不能直接调用pre.wait()因为这样会让当前线程由于进行等待态且无法被唤醒导致程序无法正常结束
pre.notifyAll();
} else {
pre.wait();//这里保证了每次只打印1次,wait()使当前线程进行等待态,且同时释放掉pre的锁
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[]args) throws InterruptedException {
Object A = new Object();
Object B = new Object();
Object C = new Object();
ThreadPrinter pa = new ThreadPrinter("a",C,A);
ThreadPrinter pb = new ThreadPrinter("b",A,B);
ThreadPrinter pc = new ThreadPrinter("c",B,C);
new Thread(pa).start();
Thread.sleep(10);
new Thread(pb).start();
Thread.sleep(10);
new Thread(pc).start();
Thread.sleep(10);
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-64030.html