多线程依次循环打印数据

时间:2021-12-31 18:32:05

如A,B,C,D, A,C,C,D....
方法很多,写一个可以运行的

package com.test.thread;

import java.util.concurrent.Semaphore;

/**
 * 三个线程,依次循环输出ABC
 *
 * Created by root on 2016/10/9.
 */
public class MutiThreadTest {

    public static void main(String[] args){
        int length = 8;

        Semaphore[] s = new Semaphore[length];
        for(int i = 0 ; i < length; i++ ){
            s[i] = new Semaphore(0);
        }
        // 先放一个信号量进去
        s[0].release();

        PrintThread[] threads = new PrintThread[length];
        for(int i = 0 ; i < length; i++ ){
            threads[i] = new PrintThread((char) ('A' + i) + "" , s[i], s[(i+1) % length]);
            threads[i].start();
        }

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class PrintThread extends Thread {
    String label = "";
    Semaphore cur;
    Semaphore next;

    public PrintThread(String label, Semaphore cur, Semaphore next){
        super();
        this.label = label;
        this.cur = cur;
        this.next = next;
    }

    @Override
    public void run() {
        while(true){
            try {
                cur.acquire();
                System.out.println(label);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                next.release();
            }
        }
    }
}