三个及以上线程间通信(以三个为例)
法① : 利用jdk1.5新特性(互斥锁)
package com.demo.reentranlock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* <p>
* Title: ReentranLockDemo
* </p>
* <p>
* Description: 循环打印step1、step2、step3
* </p>
* <p>
* Company: buaa
* </p>
*
* @author 夜色
* @date 2016年11月28日
*/
public class ReentranLockDemo {
public static void main(String[] args) {
Printer p = new Printer();
new Thread() {
public void run() {
try {
while (true) {
p.print1();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
while (true) {
p.print2();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
while (true) {
p.print3();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
class Printer {
private ReentrantLock rLock = new ReentrantLock();
private Condition c1 = rLock.newCondition();
private Condition c2 = rLock.newCondition();
private Condition c3 = rLock.newCondition();
private int flag = 1;
public void print1() throws InterruptedException {
rLock.lock();
if (flag != 1)
c1.await();
System.out.println("step 1");
flag = 2;
c2.signal();
rLock.unlock();
}
public void print2() throws InterruptedException {
rLock.lock();
if (flag != 2)
c2.await();
System.out.println("step 2");
flag = 3;
c3.signal();
rLock.unlock();
}
public void print3() throws InterruptedException {
rLock.lock();
if (flag != 3)
c3.await();
System.out.println("step 3");
flag = 1;
c1.signal();
rLock.unlock();
}
}
法②: 利用notifyAll、wait(jdk1.5之前的解决策略)
package com.demo.notifyall;
/**
*
* <p>
* Title: ReentranLockDemo
* </p>
* <p>
* Description: 循环打印step1、step2、step3
* </p>
* <p>
* Company: buaa
* </p>
*
* @author 夜色
* @date 2016年11月28日
*/
public class NotifyAllDemo {
public static void main(String[] args) {
Printer p = new Printer();
new Thread() {
public void run() {
try {
while (true) {
p.print1();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
while (true) {
p.print2();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
while (true) {
p.print3();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
class Printer {
private int flag = 1;
public void print1() throws InterruptedException {
synchronized (this) {
while (flag != 1) {
this.wait();
}
System.out.println("step 1");
flag = 2;
this.notifyAll();
}
}
public void print2() throws InterruptedException {
synchronized (this) {
while (flag != 2) {
this.wait();
}
System.out.println("step 2");
flag = 3;
this.notifyAll();
}
}
public void print3() throws InterruptedException {
synchronized (this) {
while (flag != 3) {
this.wait();
}
System.out.println("step 3");
flag = 1;
this.notifyAll();
}
}
}
对比两种方式,体会jdk1.5在进程通信上的改进