Java多線程:用三個線程控制循環輸出10次ABC

轉載:http://www.cnblogs.com/gaopeng527/p/5257884.htmlhtml

題目:有A,B,C三個線程, A線程輸出A, B線程輸出B, C線程輸出C,要求, 同時啓動三個線程, 按順序輸出ABC, 循環10次。java

解題思路:要按順序輸出ABC, 循環10次,就要控制三個線程同步工做,也就是說要讓三個線程輪流輸出,直到10個ABC所有輸出則結束線程。這裏用一個Lock對象來控制三個線程的同步。用一個int型變量COUNT標識由那個線程輸出。ide

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
相關文章
相關標籤/搜索