多个线程顺序进行和轮询进行的问题

来源:互联网 发布:反电信网络诈骗宣传片 编辑:程序博客网 时间:2024/06/04 23:18

废话不说了,晚上看到一个问题,需要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();// 三个conditionfinal Condition aCon = rLock.newCondition();final Condition bCon = rLock.newCondition();final Condition cCon = rLock.newCondition();//线程aThread a = new Thread(new Runnable() {public void run() {try {//先给第一个线程加上一段时间,给bc 线程 加锁 ,加信号Thread.sleep(500);} catch (InterruptedException e2) {// TODO Auto-generated catch blocke2.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");//线程bThread b = new Thread(new Runnable() {public void run() {for (int i = 0; i < 3; i++) {try {// 加上锁rLock.lock();try {//等待bconbCon.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");//线程cThread c = new Thread(new Runnable() {public void run() {for (int i = 0; i <3; i++) {try {// 加上锁rLock.lock();try {//等待cconcCon.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 一起对比介绍!


0 0
原创粉丝点击