线程交互java
例子:如今须要计算1+2+3+...+100,其中A线程负责计算,B线程负责展现计算结果。这样的话B线程必须等到A线程计算完结果后后才能执行,A也要将本身计算完状态通知B,因此A、B须要交互。
ide
//B线程负责展现计算结果 public class ThreadB { public static void main(String[] args) { ThreadA a = new ThreadA(); a.start(); synchronized (a){ System.out.println("等待对象b完成计算~~~"); try { b.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("b对象计算的总和是:" + a.total); } } } //A线程负责计算 public class ThreadA extends Thread { int total; @Override public void run() { synchronized (this) { for (int i = 1; i <= 100; i++) { total += i; } } notify(); } } //计算结果 等待对象b完成计算。。。 b对象计算的总和是:5050
上面的例子是A线程计算,B线程获取结果,若是如今是C、D也要获取结果该如何处理,其实很简单将notify()改成notifyAll();this
例子以下:spa
//计算器 public class Calculator extends Thread { int total; @Override public void run() { synchronized (this){ for(int i = 0; i < 101; i++){ total += i; } //注意notifyAll()必须是在synchronized中,要否则会报错,具体下篇分析 notifyAll(); } } } //获取计算结果 public class ReaderResult extends Thread { Calculator c; public ReaderResult(Calculator c) { this.c = c; } @Override public void run() { synchronized (c) { try { System.out.println(Thread.currentThread() + "等待计算结..."); c.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread() + "计算结果为:" + c.total); } } public static void main(String[] args) { Calculator calculator = new Calculator(); //启动三个线程,获取计算结果 new ReaderResult(calculator).start(); new ReaderResult(calculator).start(); new ReaderResult(calculator).start(); //启动计算线程 calculator.start(); } } //执行结果 Thread[Thread-1,5,main]等待计算结... Thread[Thread-3,5,main]等待计算结... Thread[Thread-2,5,main]等待计算结... Thread[Thread-2,5,main]计算结果为:5050 Thread[Thread-3,5,main]计算结果为:5050 Thread[Thread-1,5,main]计算结果为:5050
此处用到了synchronized关键字,下篇介绍线程同步时,具体介绍synchronized。线程