下面程序代码通过使用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(); } } }
执行结果如下: