您的位置:首页 > 编程语言 > Java开发

Java控制3个线程顺序执行2次

2014-11-12 15:32 447 查看

1、Demo

package com.fedomn.demo;

import java.util.concurrent.Semaphore;

public class semDemo{
public static void main(String[] args) {

final Semaphore semA = new Semaphore(1);
final Semaphore semB = new Semaphore(1);
final Semaphore semC = new Semaphore(1);

Thread T1 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<2;i++){
try {
semA.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A thread !");
semB.release();
}
}
});
Thread T2 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<2;i++){
try {
semB.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B thread !");
semC.release();
}
}
});
Thread T3 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<2;i++){
try {
semC.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C thread !");
semA.release();
}
}
});

try {
semB.acquire();
semC.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
T1.start();
T2.start();
T3.start();
}
}

2、输出结果

A thread !
B thread !
C thread !
A thread !
B thread !
C thread !
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程