---
title: "java使用三个线程，按顺序线程1输出1、线程2输出2、线程3输出3"
author: "XinTeng2012"
date: "2014-11-06T10:10:00Z"
tags: []
slug: "java-1-1-2-2-3-3"
draft: false
lastmod: "2015-04-02T15:08:42Z"
id: 2198206
url: "https://xinteng2012.iteye.com/blog/2198206"
---

研究了一下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();

		// thread1
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				while (state <= 30) {
					try {
						// 加锁
						lock.lock();
						if (state % 3 == 0) {
							System.out.print("1");
							state++;
						}
					}
					finally {
						lock.unlock();
					}

				}
			}
		});

		// thread2
		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				while (state <= 30) {
					try {
						// 加锁
						lock.lock();
						if (state % 3 == 1) {
							System.out.print("2");
							state++;
						}
					}
					finally {
						lock.unlock();
					}
				}
			}
		});

		// thread3
		Thread t3 = new Thread(new Runnable() {

			@Override
			public 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();
	}

}
```