题目:设计四个线程,两个线程执行加操作,两个线程执行减操作
代码如下:
public class test1 { public static void main(String[] args) { Resource res = new Resource(); SubThread st = new SubThread(res); AddThread at = new AddThread(res); new Thread(at,"加法线程-A").start(); new Thread(at,"加法线程-B").start(); new Thread(st,"减法线程-X").start(); new Thread(st,"减法线程-Y").start(); } } class AddThread implements Runnable{ private Resource resource; public AddThread(Resource resource) { this.resource = resource; } @Override public void run() { for(int x = 0;x < 10; x++) { try { this.resource.add(); } catch (Exception e) { e.printStackTrace(); } } } } class SubThread implements Runnable{ private Resource resource; public SubThread(Resource resource) { this.resource = resource; } @Override public void run() { for(int x = 0;x<10;x++) { try { this.resource.sub(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /* * 定义一个操作资源 */ class Resource{ private int num = 0; //用作加减的数据 private boolean flag = true; //加减的切换 public synchronized void add() throws Exception { if(this.flag == false) { super.wait(); return; } Thread.sleep(200); this.num ++; System.out.println("【加法操作 - "+Thread.currentThread().getName()+"】num = "+""+ this.num+" falg = "+this.flag); this.flag = false; super.notifyAll(); } public synchronized void sub() throws Exception { if(this.flag == true) { super.wait(); return; } Thread.sleep(100); this.num --; System.out.println("【减法操作 - "+Thread.currentThread().getName()+"】num = "+""+ this.num+" falg = "+this.flag); this.flag = true; super.notifyAll(); } }
多线程demo其实很容易就搭建起来,但是你要做到同步加减使得num的值在0,1之间变换,需要动一点脑筋,设置一个布尔类型的flag,来判断加减的切换,当flag=true的时候你做加法,flase的时候做减法,否则wait()等待,代码操作如下:
if(this.flag == false) { super.wait(); return; } ...省略add() this.flag = false; super.notifyAll();
做完加/减法后在切换flag,并且释放所有等待的线程。一开始忘记设置return,导致方法继续往下做下去而没有做到同步加减法使得num在0,1之间切换。不过最后还是发现了小小的bug。结果如下:
【加法操作 - 加法线程-B】num = 1 falg = true 【减法操作 - 减法线程-Y】num = 0 falg = false 【加法操作 - 加法线程-A】num = 1 falg = true 【减法操作 - 减法线程-X】num = 0 falg = false 【加法操作 - 加法线程-A】num = 1 falg = true 【减法操作 - 减法线程-Y】num = 0 falg = false 【加法操作 - 加法线程-B】num = 1 falg = true 【减法操作 - 减法线程-X】num = 0 falg = false 【加法操作 - 加法线程-B】num = 1 falg = true 【减法操作 - 减法线程-Y】num = 0 falg = false 【加法操作 - 加法线程-A】num = 1 falg = true 【减法操作 - 减法线程-X】num = 0 falg = false 【加法操作 - 加法线程-B】num = 1 falg = true 【减法操作 - 减法线程-Y】num = 0 falg = false 【加法操作 - 加法线程-A】num = 1 falg = true 【减法操作 - 减法线程-X】num = 0 falg = false