使用某种形式的锁定机制仅在尚未执行任务时执行它。获取锁定令牌必须是一个一步的过程。看到:
public abstract class NonconcurrentTask implements Runnable { private boolean token = true; private synchronized boolean acquire() { boolean ret = token; token = false; return ret; } private synchronized void release() { token = true; } public final void run() { if (acquire()) { try { doTask(); } finally { release(); } } } protected abstract void doTask();}如果任务同时运行,将抛出异常的测试代码:
public class Test { public static void main(String[] args) { final NonconcurrentTask shared = new NonconcurrentTask() { private boolean working = false; protected void doTask() { System.out.println("Working: " + Thread.currentThread().getName()); if (working) { throw new IllegalStateException(); } working = true; try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } if (!working) { throw new IllegalStateException(); } working = false; } }; Runnable taskWrapper = new Runnable() { public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } shared.run(); } } }; for (int i = 0; i < 100; i++) { new Thread(taskWrapper).start(); } }}


