曾经面试的时候,做过这道题目,不会做,一直耿耿于怀,现在刚好在看JDK5的并发包,可以这样做:
package abcthread; import java.util.concurrent.Semaphore; public class Test { private static boolean[] flags = new boolean[3]; private static Semaphore sm = new Semaphore(1,true); private static final String[] strArr = {"A", "B", "C"}; private static final int COUNT = 10; public static void main(String[] args) { flags[0] = true; for(int i = 0 ;i < 3; i ++) { MyThread a = new MyThread(i); a.setName(strArr[i]); a.start(); } } private static class MyThread extends Thread { private int order; public MyThread(int i) { order = i; } public void run() { int count = COUNT; while(count > 0) { if(sm.tryAcquire()) { if(flags[order]) { System.out.println(getName()); count --; flags[order] = false; flags[(order+1) % 3] = true; } sm.release(); } } } } }
有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC
最新推荐文章于 2021-10-07 22:22:39 发布