下面的程序演示了一个对象被两个线程访问的方法,"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();
也是一种常用的多个线程共享数据的方式,
本文通过示例代码展示了如何使用Java实现线程间的同步操作及多个线程共享数据的具体方式。介绍了BusyWaiting类中创建Monitor和MyObject对象,并启动线程的方法;Monitor类和MyObject类中定义了线程间通信所需的方法。

609

被折叠的 条评论
为什么被折叠?



