您的位置:首页 > 编程语言 > Java开发

Java多线程之间通信——修改对象中的成员变量

2014-12-20 12:45 239 查看
线程之间的通信,可通过对对象的成员变量的状态修改,达到控制线程的目的。

Java中,线程要基于对象才能创建。如:

ThreadTest t1 = new ThreadTest();

t1.start();//启动一个线程,并运行ThreadTest 中的run()方法

如何对另外一个线程的状态控制,通过传入另外那个对象的实例,然后调用另外这个对象的私有函数,该私有函数内改变成员变量的状态。

为什么是私有函数,是为了达到更好的封装的目的。

程序如下:

package Multithread;

//import java.util.concurrent.*;

class ThreadObject1 implements Runnable {

    private ThreadObject2 threadObject2 ;

    public ThreadObject1(ThreadObject2 threadObject2) {  //传入另外一个对象ThreadObject2

      this.threadObject2 = threadObject2 ;

    }

    public void run() {

      try {

        //TimeUnit.SECONDS.sleep(3);

        System.out.println("i'm going.");

        threadObject2.SendMessage();     //修改另外对象ThreadObject2的成员变量,从而改变基于threadObject2对象的线程的运行状态

      } catch (InterruptedException e) {

        e.printStackTrace();

      }

    }

}

class ThreadObject2 implements Runnable {

    private volatile boolean go = false;

    public void SendMessage() throws InterruptedException {  //修改成员变量状态

      go = true;
    }

    public void waiting() {     //忙等待,遇到go的状态变为true则跳出循环。

      while (go == false)

        ;

      System.out.println("He has gone.");

    }

    public void run() {

      waiting();

    }

}

public class BusyWaiting {

    public static void main(String[] args) {

      ThreadObject2 threadObject2 = new ThreadObject2();

      ThreadObject1 threadObject1 = new ThreadObject1(threadObject2);

      new Thread(threadObject1).start();

      new Thread(threadObject2).start();

    }
}

程序运行结果:

i'm going.

He has gone.

以上其实总共有三个线程,一个主线程,两个子线程。对于希望简化只需要通过主线程控制子线程中断的话,可以通过如下代码实现。

class Example2 extends Thread {
volatile boolean stop = false;// 线程中断信号量

public static void main(String args[]) throws Exception {
Example2 thread = new Example2();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
// 设置中断信号量
thread.stop = true;
Thread.sleep(3000);
System.out.println("Stopping application...");
}

public void run() {
// 每隔一秒检测一下中断信号量
while (!stop) {
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
/*
* 使用while循环模拟 sleep 方法,这里不要使用sleep,否则在阻塞时会 抛
* InterruptedException异常而退出循环,这样while检测stop条件就不会执行,
* 失去了意义。
*/
while ((System.currentTimeMillis() - time < 1000)) {}
}
System.out.println("Thread exiting under request...");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 多线程