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

线程之间的通信,可通过对对象的成员变量的状态修改,达到控制线程的目的。

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...");
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值