Java多线程间的数据共享
下面的程序演示了一个对象被两个线程访问的方法,"monitor.gotMessage();"这一句虽然是monitor对象的方法,但却是运行在"MyObject"的线程里,而不是"monitor"线程里。 BusyWaiting.java:
public class BusyWaiting { public static void main(String[] args) { Monitor monitor = new Monitor(); MyObject o = new MyObject(monitor); new Thread(o, " MyObject ").start(); new Thread(monitor, " monitor ").start(); System.out.println("main thread exit..."); } }
MyObject.java
import java.util.concurrent.TimeUnit; public class MyObject implements Runnable { private final Monitor monitor; public MyObject(Monitor monitor) { this.monitor = monitor; } public void run() { try { TimeUnit.SECONDS.sleep(3); System.out.println("i'm going."); monitor.gotMessage(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Monitor.java
public class Monitor implements Runnable { private volatile boolean go = false; public void gotMessage() throws InterruptedException { go = true; } public void watching() { while (go == false) ; System.out.println("He has gone."); } public void run() { watching(); } }
另外采用
MyObject o = new MyObject(monitor); new Thread(o, " thread1 ").start(); new Thread(o, "thread2").start();
也是一种常用的多个线程共享数据的方式,