您的位置:首页 > 其它

多线程依次循环打印数据

2016-10-09 17:05 429 查看
如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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: