【多线程】线程间通信

等待通知机智的实现

方法wait()的作用是使当前执行代码的线程进行等待,wait()方法是Object类的方法,该方法用来将当前线程置入“预执行队列”中,并且在wait()所在的代码行处停止执行,直到接到通知或被中断为止。

在调用wait()之前,线程必须获得该对象的对象级别锁,即只能在同步方法或同步块中调用wait()方法。

在执行wait()方法后,当前线程释放锁。

如果调用wait()是没有持有适当的锁,则抛出IIegalMonitorStateException,它是RuntimeException的一个子类。

方法notify()也要在同步方法或同步代码块中调用,即在调用前,线程也必须获得该对象的对象级别锁。

该方法用来通知那些可能等待该对象的对象锁的其他线程,如果有多个线程等待,则由线程规划器随机挑选出其中一个呈wait状态的线程,对其发出通知notify,并使它等待获取该对象的对象锁。

 

需要说明的是,在执行notify()方法后,当前线程不会马上释放该对象锁,呈wait状态的线程也并不能马上获取该对象锁,要等到执行notify()方法的线程将程序执行完,也就是退出synchronized代码块后,当前线程才会释放锁,而呈wait状态的线程才可以获取该对象的锁。

当第一个获得了该对象锁的wait线程运行完毕后,他会释放掉该对象锁,此时如果该对象没有再次使用notify语句,则即便该对象已经空闲,其他wait状态等待的线程由于没有得到该对象的通知,还会继续阻塞在wait状态,直到这对象发出一个notify或notifyall.

用一句话来总结一下wait和notify:

wait使线程停止运行,而notify使停止的线程继续运行。

 

以上说法创建测试项目

wait_notify_size5

创建MyList类

public class MyList {

    private static List list = new ArrayList();

    public static void add() {
        list.add("anything");
    }

    public static int size() {
        return list.size();
    }
}

类ThreadA

public class ThreadA extends Thread {
    private Object lock;
    public ThreadA(Object lock){
        super();
        this.lock = lock;
    }

    @Override
    public void run() {

        try {
            synchronized (lock){
                if(MyList.size() != 5){
                    System.out.println("wait begin"+System.currentTimeMillis());
                    lock.wait();
                    System.out.println("wait end"+ System.currentTimeMillis());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

类ThreadB

public class ThreadB extends Thread {
    private Object lock;

    public ThreadB(Object lock) {
        super();
        this.lock = lock;
    }

    @Override
    public void run() {

        try {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    MyList.add();
                    if (MyList.size() == 5) {
                        lock.notify();
                        System.out.println("已发出通知");

                    }
                    System.out.println("添加了" + (i + 1) + "个元素!");
                    Thread.sleep(1000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

类Run

public class Run {

    public static void main(String[] args) {

        try {
            Object lock = new Object();
            ThreadA a = new ThreadA(lock);
            a.start();
            Thread.sleep(50);
            ThreadB b = new ThreadB(lock);
            b.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果如下

日志信息 wait end 在最后输出,这也说明notify()方法执行后并不是立即释放锁。

关键字synchronized可以将任何一个Object对象作为同步对象来看待,而java为每个对象都实现了wait()和notify()方法,它们必须用在被synchronized同步的Object的临界区内。通过调用wait()方法可以使处于临界区内的线程进入等待状态,同时释放被同步对象的锁。而notify操作可以唤醒一个因调用了wait操作而处于阻塞状态的线程,使其进入就绪状态。被重新唤醒的线程会试图重新获得临界区的控制权,也就是锁,并继续执行临界区内wait之后的代码。

如果发出的notify操作时没有处于阻塞状态中的线程,那么该命令就会被忽略。

 

wait()方法可以使用调用该方法的线程释放共享资源的锁,然后从运行状态退出,进入等待队列,直到被再次唤醒。

 

notify()方法可以随机唤醒等待队列中等待同一共享资源的“一个”线程,并是该线程退出等待队列,进入可运行状态,也就是notify()方法仅通知“一个”线程。

 

notifyAll()方法可以使所有正在等待队列中等待同一共享资源的“全部”线程从等待状态退出,进入可运行状态。此时,优先级最高的那个线程最先执行,但也有可能是随机执行,因为这要取决于JVM虚拟机的实现。

 

方法notify()被执行后,不释放锁,必须执行完notify()方法所在的同步代码块synchronized代码块后才释放锁。

当线程呈wait()状态时,调用线程对象的interrupt()方法会出现InterruptedException异常。

 

方法notify()仅随机唤醒一个线程。

当多次调用notify()方法时,会随机将等待wait状态的线程进行唤醒。

 

notifyAll()唤醒所有的线程

wait(long)

方法wait(long)的功能是等待某一段时间内是否有线程对锁进行唤醒,如果超过这个时间则自动唤醒。

通过管道进行线程间通信:字节流

 

管道流是一种特殊的流,用于在不同线程间直接传送数据。一个线程发送数据到输出管道,另一个线程从输入管道中读数据。通过使用管道,实现不同线程间的通信,而无需借助于累死临时文件之类的东西。

在Java的jdk中提供了4个类来使线程间可以进行通信:

1)PipedInputStream和PipedOutputStream

2)PipedReader和PipedWriter

创建测试项目pipeInputOutPut

类ReadData
public class ReadData {
    public void readMethod(PipedInputStream input){

        try {
            System.out.println("read :");
            byte[] byteArray = new byte[20];

            int readLength = input.read(byteArray);

            while (readLength != -1){
                String newData = new String(byteArray, 0, readLength);
                System.out.println("读取到:"+newData);
                readLength = input.read(byteArray);
            }
            System.out.println();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

类WriteData

public class WriteData {
    public void writeMethod(PipedOutputStream out){
        try {
            System.out.println("write :");
            for (int i = 0; i < 300; i++) {
                String outData = ""+(i+1);
                out.write(outData.getBytes());
                System.out.println("写入:"+outData);
            }
            System.out.println();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

类ThreadRead

public class ThreadRead extends Thread {

    private ReadData read;
    private PipedInputStream input;

    public ThreadRead(ReadData read, PipedInputStream input) {

        super();
        this.read = read;
        this.input = input;
    }

    @Override
    public void run() {
        read.readMethod(input);
    }
}

类ThreadWrite

public class ThreadWrite extends Thread {

    private WriteData write;
    private PipedOutputStream out;

    public ThreadWrite(WriteData write, PipedOutputStream out){
        super();
        this.write = write;
        this.out = out;
    }

    @Override
    public void run() {
        write.writeMethod(out);
    }
}

类Run

public class Run {

    public static void main(String[] args) {

        try {
            WriteData writeData = new WriteData();
            ReadData readData = new ReadData();
            PipedInputStream inputStream = new PipedInputStream();
            PipedOutputStream outputStream = new PipedOutputStream();

            //使两个Stream之间产生通信链接,这样才可以将数据进行输出与输入
            outputStream.connect(inputStream);
            ThreadRead threadRead = new ThreadRead(readData, inputStream);
            threadRead.start();
            Thread.sleep(2000);
            ThreadWrite threadWrite = new ThreadWrite(writeData, outputStream);
            threadWrite.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果

 

通过管道进行线程间通信:字符流

创建测试项目

pipeReaderWriter
类ReadData
public class ReadData {

    public void readMethod(PipedReader input) {
        try {
            System.out.println("read: ");
            char[] byteArray = new char[20];
            int readLength = input.read(byteArray);
            while (readLength != -1) {
                String newData = new String(byteArray, 0, readLength);
                System.out.println("读数据:"+newData);
                readLength = input.read(byteArray);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

类WriteData

public class WriteData {

    public void writeMethod(PipedWriter out) {
        try {
            System.out.println("write: ");
            for (int i = 0; i < 300; i++) {
                String outData = "" + (i + 1);
                out.write(outData);
                System.out.println("写入数据:"+outData);
            }
            System.out.println();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

类ThreadRead

public class ThreadRead extends Thread {


    private ReadData read;
    private PipedReader input;

    public ThreadRead(ReadData read, PipedReader input) {
        super();
        this.read = read;
        this.input = input;
    }

    @Override
    public void run() {
        read.readMethod(input);
    }
}

类ThreadWrite

public class ThreadWrite extends Thread {

    private WriteData write;
    private PipedWriter out;

    public ThreadWrite(WriteData write, PipedWriter out){
        super();
        this.write = write;
        this.out = out;
    }

    @Override
    public void run() {
     write.writeMethod(out);
    }
}

类Run

public class Run {
    public static void main(String[] args) {
        try {
            WriteData writeData = new WriteData();
            ReadData readData = new ReadData();
            PipedReader inputStream = new PipedReader();
            PipedWriter outputStream = new PipedWriter();
            outputStream.connect(inputStream);
            ThreadRead threadRead = new ThreadRead(readData, inputStream);
            threadRead.start();
            Thread.sleep(2000);
            ThreadWrite threadWrite = new ThreadWrite(writeData, outputStream);
            threadWrite.start();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

运行结果

join()方法的使用

作用说明:

如果子线程中要进行大量的耗时运算,主线程往往早于子线程结束之前结束。这时,如果主线程想等待子线程执行完成之后再结束,比如子线程处理一个数据,主线程要取得这个数据中的值,就要用到join()方法了。

join()的作用就是等待线程对象销毁。

创建测试项目

joinTest

 

创建类

MyThread
public class MyThread extends Thread {

    @Override
    public void run() {
        try {
            int secondValue = (int) (Math.random() * 10000);
            System.out.println(secondValue);
            Thread.sleep(secondValue);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

创建类

Test
public class Test {
    public static void main(String[] args) {

        try {
            MyThread threadTest = new MyThread();
            threadTest.start();
            threadTest.join();
            System.out.println("我想当ThreadTest对象执行完毕后我再执行,我做到了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果

结论:

方法join具有使线程排队运行的作用,有些类似同步的运行效果。join与synchronized的区别是:join在内部使用wait()方法进行等待,而sychronized关键字使用的是“对象监视器”原理作为同步。

 

join(long)参数是设定等待时间。

join(long)与sleep(long)的区别

  • 方法join(long)的功能在内部是使用wait(long)方法来实现的,所以join(long)方法具有释放锁的特点。
  • sleep(long)方法不释放锁

类ThreadLocal的使用

类ThreadLoacal主要解决的就是每个线程都绑定自己的值,可以将ThreadLocal类比喻成全局存放数据的盒子,盒子中可以存储每个线程的私有数据。

类ThreadLocal解决的是变量在不同线程间的隔离性,也就是不同线程拥有自己的值,不同线程中的值可以放入ThreadLocal类中进行保存的。

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值