废话不说了,晚上看到一个问题,需要ABC线程,能依次打印ABC(需要循环的)?
之前看能没有看到它需要循环打出这些,只是觉得他要顺序打出,所以就用了join 这个关键字做了一个demo;
package com.zeng.thread;
/**
* 实现三个线程ABC,按照顺序输出ABC
* 方案一
*
* @author leo-zeng
*
*/
public class Test1 {
public static void main(String[] args) throws Exception {
//A 线程
Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("A");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A");
//b线程
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("B");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B");
//C 线程
Thread t3 = new Thread(new Runnable() {
public void run() {
System.out.println("C");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C");
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
}
}
打印出的结果是ABC
后来仔细一看,不满足,问题的条件是需要循环打出ABC,所以用join 是不满足的,这会只能用到lock,通过condition来满足这个需求;下面也写了这个demo,
demo比较简单,通过一个reentrantLock 和 condition 的await 和single 方法,进行线程间的轮询,来达到结果;看下demo吧!
package com.zeng.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Abc 三个线程分别输出循环输出 abc 用reentrantLock
*
* @author leo-zeng
*
*/
public class ReentrantLockDemo {
public static void main(String[] args) {
// 重入锁
final ReentrantLock rLock = new ReentrantLock();
// 三个condition
final Condition aCon = rLock.newCondition();
final Condition bCon = rLock.newCondition();
final Condition cCon = rLock.newCondition();
//线程a
Thread a = new Thread(new Runnable() {
public void run() {
try {
//先给第一个线程加上一段时间,给bc 线程 加锁 ,加信号
Thread.sleep(500);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
for (int i = 0; i < 3; i++) {
try {
// 加上锁
rLock.lock();
System.out.println("A");
Thread.sleep(1000);
// 打印完A 之后 关闭a 给b 信号
bCon.signal();
//等待一个a给的信号
try {
aCon.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 解锁
rLock.unlock();
}
}
}
}, "A");
//线程b
Thread b = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
try {
// 加上锁
rLock.lock();
try {
//等待bcon
bCon.await();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("B");
Thread.sleep(1000);
// 打印完b 之后 给c 信号
cCon.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 解锁
rLock.unlock();
}
}
}
}, "B");
//线程c
Thread c = new Thread(new Runnable() {
public void run() {
for (int i = 0; i <3; i++) {
try {
// 加上锁
rLock.lock();
try {
//等待ccon
cCon.await();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("C");
Thread.sleep(1000);
// 打印完c 之后 给a 信号
aCon.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 解锁
rLock.unlock();
}
}
}
}, "C");
//a b c 线程
a.start();
b.start();
c.start();
Thread.yield();
}
}
这里就不重点介绍ReentrantLock锁了;下次再和synchronized 一起对比介绍!