50,523
社区成员
发帖
与我相关
我的任务
分享
public class Test extends Thread {
private static String currentThread = "A";
private static byte[] lock = new byte[0];
private String name = "";
private int count = 10;
public Test(String name) {
this.name = name;
}
public void run() {
while (count > 0) {
synchronized (lock) {
if (currentThread.equals(this.name)) {
System.out.println(name);
count--;
if (currentThread.equals("A")) {
currentThread = "B";
} else if (currentThread.equals("B")) {
currentThread = "C";
} else if (currentThread.equals("C")) {
currentThread = "A";
System.out.println();
}
}
}
}
}
/** * @param args */
public static void main(String[] args) {
(new Test("A")).start();
(new Test("B")).start();
(new Test("C")).start();
}
}
import java.util.concurrent.Semaphore;
public class ThreadSync {
static class ConditionThread extends Thread {
ConditionThread(Semaphore preCond, Semaphore postCond, String text) {
this.preCond = preCond;
this.postCond = postCond;
this.text = text;
}
private Semaphore preCond;
private Semaphore postCond;
private String text;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
preCond.acquire();
System.out.print(text);
postCond.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Semaphore semaphoreA = new Semaphore(0);
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(1);
Thread threadA = new ConditionThread(semaphoreC, semaphoreA, "A");
Thread threadB = new ConditionThread(semaphoreA, semaphoreB, "B");
Thread threadC = new ConditionThread(semaphoreB, semaphoreC, "C");
threadA.start();
threadB.start();
threadC.start();
threadA.join();
threadB.join();
threadC.join();
}
}