多线程题:有三个线程A,B,C, A线程输出A,B线程输出B,C线程输出C
编程要求:在屏幕上打出10个ABC串,即 ABCABCABCABCABCABCABCABCABCABC
import java.lang.Thread;
import java.lang.InterruptedException;
import java.util.concurrent.Semaphore;
public class Main{
private static Semaphore A = new Semaphore(1);
private static Semaphore B = new Semaphore(1);
private static Semaphore C = new Semaphore(1);
static class ThreadA extends Thread{
public void run() {
for (int i=0; i<10; i++){
try{
A.acquire();
} catch(InterruptedException e) {}
System.out.print("A");
B.release();
}
}
}
static class ThreadB extends Thread {
public void run() {
for(int i=0; i<10; i++) {
try {
B.acquire();
} catch (InterruptedException e) {
}
System.out.print("B");
C.release();
}
}
}
static class ThreadC extends Thread{
public void run() {
for (int i=0; i<10; i++) {
try {
C.acquire();
} catch(InterruptedException e) {}
System.out.println("C");
A.release();
}
}
}
public static void main(String [] args) throws InterruptedException{
B.acquire();
C.acquire();
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}
评论