Java线程间通过共享对象通信

来源:互联网 发布:android 无法修改mac 编辑:程序博客网 时间:2024/06/03 15:56

Java线程间通过共享对象通信

共享对象必须是对象,例如class、Integer、String之类的,不能是一般的变量,如int、double、boolean之类。

下面给出一个例子,当线程B运行10s之后通过线程A关闭线程B。


  • 主函数
public class Exercise {    public static void main(String args[]) {        ThreadStop t = new ThreadStop();        new Thread(new A(t)).start();        new Thread(new B(t)).start();    }}
  • 共享对象
public class ThreadStop {    volatile private boolean value = true;    synchronized public boolean isValue() {        return value;    }    synchronized public void setValue(boolean value) {        this.value = value;    }}
  • 线程A
public class A implements Runnable {    private ThreadStop t;    public A(ThreadStop t) {        this.t = t;    }    public void run() {        long begin = System.currentTimeMillis(), end = System.currentTimeMillis();        while (Math.abs(end - begin) < 10000) {            end = System.currentTimeMillis();        }        t.setValue(false);    }}
  • 线程B
public class B implements Runnable {    private ThreadStop t;    public B(ThreadStop t) {        this.t = t;    }    public void run() {        while (t.isValue()) {}        System.out.println(Thread.currentThread().getName() + " is stoped by another Thread");    }}
0 0
原创粉丝点击