java使用三个线程,按顺序线程1输出1、线程2输出2、线程3输出3

来源:互联网 发布:linux可执行文件格式 编辑:程序博客网 时间:2024/05/22 12:31

研究了一下Reentrantlock在并发过程中的使用,下面是实现三个线程按顺序输出1,2,3:

import java.util.concurrent.locks.ReentrantLock;/** * 标题、简要说明. <br> * 类详细说明. * <p> * Copyright: Copyright (c) 2014年11月6日 上午9:50:41 * <p> * Company:  * <p> *  * @author  * @version 1.0.0 */public class TestLock {private static int state = 0;/** * @param args */public static void main(String[] args) {final ReentrantLock lock = new ReentrantLock();// thread1Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {while (state <= 30) {try {// 加锁lock.lock();if (state % 3 == 0) {System.out.print("1");state++;}}finally {lock.unlock();}}}});// thread2Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {while (state <= 30) {try {// 加锁lock.lock();if (state % 3 == 1) {System.out.print("2");state++;}}finally {lock.unlock();}}}});// thread3Thread t3 = new Thread(new Runnable() {@Overridepublic void run() {while (state <= 30) {try {// 加锁lock.lock();if (state % 3 == 2) {System.out.println("3");state++;}}finally {lock.unlock();}}}});t1.start();t2.start();t3.start();}}



0 0