import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.concurrent.FutureTask; class Answer implements Callable<String> { private boolean flag = true; @Override public synchronized String call() throws Exception { if(flag == true) { Thread.sleep(100); flag = false; return Thread.currentThread().getName() + "抢答成功"; } else { return Thread.currentThread().getName() + "抢答失败"; } } } public class ThreadCompete { public static void main(String[] args) { Answer answer = new Answer(); FutureTask<String> task1 = new FutureTask<>(answer); FutureTask<String> task2 = new FutureTask<>(answer); FutureTask<String> task3 = new FutureTask<>(answer); new Thread(task1).start(); new Thread(task2).start(); new Thread(task3).start(); try { System.out.println(task1.get()); System.out.println(task2.get()); System.out.println(task3.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
class Resource{ private int num = 0; private boolean flag = true; public synchronized void add() { while(this.flag == false) { try { super.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.num++; System.out.println("加法操作-" + Thread.currentThread().getName() + this.num); this.flag = false; super.notifyAll(); } public synchronized void sub() { while(this.flag == true) { try { super.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { Thread.sleep(80); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.num--; System.out.println("减法操作-" + Thread.currentThread().getName() + this.num); this.flag = true; super.notifyAll(); } } class Jia implements Runnable{ private Resource resource; public Jia(Resource resource) { this.resource = resource; } @Override public void run() { for (int i = 0; i < 50; i++) { resource.add(); } } } class Jian implements Runnable{ private Resource resource; public Jian(Resource resource) { this.resource = resource; } @Override public void run() { for (int i = 0; i < 50; i++) { resource.sub();; } } } public class ThreadJiaJian { public static void main(String[] args) { Resource resource = new Resource(); Jian jian = new Jian(resource); Jia jia = new Jia(resource); new Thread(jian,"减法线程A").start(); new Thread(jian,"减法线程B").start(); new Thread(jia,"加法线程X").start(); new Thread(jia,"加法线程Y").start(); }
}