`
MouseLearnJava
  • 浏览: 459915 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

面试题 -- 一个线程打印 1~52,另一个线程打印字母A-Z。打印顺序为12A34B56C……5152Z。

阅读更多

题目:一个线程打印 1~52,另一个线程打印字母A-Z。打印顺序为12A34B56C……5152Z。

解决的方法有很多种,比如:
使用synchronized, wait和notifyAll
使用Lock 和 Condition
使用Semaphore 等。


本文采用Lock 和 Condition来实现。

程序源代码:

package my.thread.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 一个线程打印 1~52,另一个线程打印字母A-Z。打印顺序为12A34B56C……5152Z。
 * 
 * @author Eric
 * 
 */
public class ThreadCommunicationTest {

	private final Lock lock = new ReentrantLock();

	private final Condition conditionA = lock.newCondition();
	private final Condition conditionB = lock.newCondition();

	private static char currentThread = 'A';

	public static void main(String[] args) {

		ThreadCommunicationTest test = new ThreadCommunicationTest();

		ExecutorService service = Executors.newCachedThreadPool();

		service.execute(test.new RunnableA());
		service.execute(test.new RunnableB());

		service.shutdown();

	}

	private class RunnableA implements Runnable {

		public void run() {
			for (int i = 1; i <= 52; i++) {
				lock.lock();

				try {
					while (currentThread != 'A') {
						try {
							conditionA.await();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					System.out.println(i);
					if (i % 2 == 0) {
						currentThread = 'B';
						conditionB.signal();
					}
				} finally {
					lock.unlock();
				}
			}

		}

	}

	private class RunnableB implements Runnable {

		@Override
		public void run() {
			for (char c = 'A'; c <= 'Z'; c++) {
				lock.lock();
				try {
					while (currentThread != 'B') {
						try {
							conditionB.await();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					System.out.println(c);
					currentThread = 'A';
					conditionA.signal();
				} finally {
					lock.unlock();
				}
			}

		}

	}
}



程序运行结果:

1
2
A
3
4
B
5
6
C
7
8
D
9
10
E
11
12
F
13
14
G
15
16
H
17
18
I
19
20
J
21
22
K
23
24
L
25
26
M
27
28
N
29
30
O
31
32
P
33
34
Q
35
36
R
37
38
S
39
40
T
41
42
U
43
44
V
45
46
W
47
48
X
49
50
Y
51
52
Z
0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics