多线程 流水线 java_Java Lock锁多线程中实现流水线任务

下面程序代码通过使用Lock锁执行简单的流水线任务:

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

/**

* @author lzq

* @data 2020/4/29 0029 - 下午 9:48

*/

public class TestLock {

public static void main(String[] args) {

DataSource dataSource=new DataSource();

new Thread(() -> {

for (int i=0;i<10;i++){

dataSource.a();

}

},"A").start();

new Thread(() -> {

for (int i=0;i<10;i++){

dataSource.b();

}

},"B").start();

new Thread(() -> {

for (int i=0;i<10;i++){

dataSource.c();

}

},"C").start();

}

}

class DataSource{

private int x=1;

private Lock lock=new ReentrantLock();

private Condition condition1=lock.newCondition();

private Condition condition2=lock.newCondition();

private Condition condition3=lock.newCondition();

public void a(){

lock.lock();

try {

while(x!=1){

condition1.await();

}

System.out.println(Thread.currentThread().getName()+":aaa");

x=2;

condition2.signal();

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

public void b(){

lock.lock();

try {

while(x!=2){

condition2.await();

}

System.out.println(Thread.currentThread().getName()+":bbb");

x=3;

condition3.signal();

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

public void c(){

lock.lock();

try {

while(x!=3){

condition3.await();

}

System.out.println(Thread.currentThread().getName()+":ccc");

x=1;

condition1.signal();

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

}

执行结果如下:

a553a9a43e4f153a0dcb8f75e8b18feb.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值