Java多线程:用三个线程控制循环输出10次ABC

时间:2024-10-18 11:37:02

转载:http://www.cnblogs.com/gaopeng527/p/5257884.html

题目:有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C,要求, 同时启动三个线程, 按顺序输出ABC, 循环10次。

解题思路:要按顺序输出ABC, 循环10次,就要控制三个线程同步工作,也就是说要让三个线程轮流输出,直到10个ABC全部输出则结束线程。这里用一个Lock对象来控制三个线程的同步。用一个int型变量COUNT标识由那个线程输出。

package cn.com.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* Created by Jack on 2017/2/13.
*/
public class PrintABC { // 有3个线程ABC。按照ABC来运行(A线程输出A,B线程输出B,C线程输出C,以此类推,循环输出)。 public static int cnt = 0;
public static final int COUNT = 30; public static void main(String[] args) { final Lock lock = new ReentrantLock();
Thread A = new Thread(new Runnable() { @Override
public void run() {
while (true) {
lock.lock();
if (cnt >= COUNT) {
lock.unlock();
return;
}
if (cnt % 3 == 0) {
System.out.println("A");
cnt++;
}
lock.unlock();
}
} }); Thread B = new Thread(new Runnable() {
public void run() {
while (true) {
lock.lock();
if (cnt >= COUNT) {
lock.unlock();
return;
}
if (cnt % 3 == 1) {
System.out.println("B");
cnt++;
}
lock.unlock();
}
}
}); Thread C = new Thread(new Runnable() {
public void run() {
while (true) {
lock.lock();
if (cnt >= COUNT) {
lock.unlock();
return;
}
if (cnt % 3 == 2) {
System.out.println("C");
cnt++;
}
lock.unlock();
}
}
});
A.start();
B.start();
C.start();
} }

输出:

A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C