java信号量控制线程打印顺序的示例分享
import java.util.concurrent.semaphore;
public class threethread {
public static void main(string[] args) throws interruptedexception {
semaphore sempa = new semaphore(1);
semaphore sempb = new semaphore(0);
semaphore sempc = new semaphore(0);
int n=100;
thread threada = new printthread(n, sempa, sempb, "a");
thread threadb = new printthread(n, sempb, sempc, "b");
thread threadc = new printthread(n, sempc, sempa, "c");
threada.start();
threadb.start();
threadc.start();
}
static class printthread extends thread{
int n;
semaphore cursemp;
semaphore nextsemp;
string name;
public printthread(int n, semaphore cursemp, semaphore nextsemp, string name) {
n = n;
this.cursemp = cursemp;
this.nextsemp = nextsemp;
this.name = name;
}
public void run() {
for (int i = 0; i < n; ++i) {
try {
cursemp.acquire();
system.out.println(name);
nextsemp.release();
} catch (interruptedexception e) {
thread.currentthread().interrupt();
}
}
}
}
}
上一篇: Android开发之关于项目
下一篇: java poi解析word的方法