欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

线程通信

程序员文章站 2022-05-21 10:57:30
1. wait / notify 要想执行 wait() / notify() / notifyAll() 这些方法,必须首先获得对象的监视器 换言之,这些方法必须在 synchronized 中执行 2. Condition 3. wait() Causes the current thread ......

1.  wait / notify

要想执行 wait() / notify() / notifyall() 这些方法,必须首先获得对象的监视器

换言之,这些方法必须在 synchronized 中执行

package com.example.demo22;

import java.util.linkedlist;

public class app2 {

    public static void main(string[] args) {

        final factory factory = new factory();

        thread producer = new thread(new runnable() {
            @override
            public void run() {
                try {
                    while (true) {
                        factory.offer();
                    }
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        });
        thread consumer = new thread(new runnable() {
            @override
            public void run() {
                try {
                    while (true) {
                        factory.take();
                    }
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }


}

class factory {

    private linkedlist<object> container = new linkedlist<>();

    private integer capacity = 5;

    public synchronized void offer() throws interruptedexception {
        while (container.size() == capacity) {
            wait();
        }

        int e = (int) math.ceil(math.random() * 100);
        container.push(e);
        system.out.println("生产" + e);
        notify();
    }


    public synchronized void take() throws interruptedexception {
        while (container.size() == 0) {
            wait();
        }

        object e = container.poll();
        system.out.println("消费" + e);
        notify();
    }

}

2.  condition  

package com.example.demo22;

import java.util.concurrent.locks.condition;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;

public class app {

    public static void main(string[] args) {
        final worker worker = new worker();

        new thread(new runnable() {
            @override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    worker.red();
                }
            }
        }).start();
        new thread(new runnable() {
            @override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    worker.green();
                }
            }
        }).start();
        new thread(new runnable() {
            @override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    worker.yellow();
                }
            }
        }).start();

    }

}

class worker {

    private final lock lock = new reentrantlock();
    private final condition conditiona = lock.newcondition();
    private final condition conditionb = lock.newcondition();
    private final condition conditionc = lock.newcondition();

    private integer signal = 1;


    public void red() {
        lock.lock();
        try {
            while (signal != 1) {
                conditiona.await();
            }
            system.out.println("red");
            signal = 2;
            conditionb.signal();
        } catch (interruptedexception e) {
            e.printstacktrace();
        } finally {
            lock.unlock();
        }
    }

    public void green() {
        lock.lock();
        try {
            while (signal != 2) {
                conditionb.await();
            }
            system.out.println("green");
            signal = 3;
            conditionc.signal();
        } catch (interruptedexception e) {
            e.printstacktrace();
        } finally {
            lock.unlock();
        }
    }

    public void yellow() {
        lock.lock();
        try {
            while (signal != 3) {
                conditionc.await();
            }
            system.out.println("yellow");
            signal = 1;
            conditiona.signal();
        } catch (interruptedexception e) {
            e.printstacktrace();
        } finally {
            lock.unlock();
        }
    }

}

3.  wait()

causes the current thread to wait until another thread invokes the notify() method or the notifyall() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

the current thread must own this object's monitor. the thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyall method. the thread then waits until it can re-obtain ownership of the monitor and resumes execution.

调用wait()方法会造成当前线程等待,直到另一个线程调用这个对象的notify()或者notifyall()方法,或者其它线程打断当前线程,或者时钟周期耗尽。

调用wait()方法必须当前线程首先获得这个对象的监视器。线程释放对象的监视器的所有权,并等待直到另一个线程通知由于这个对象的监视器造成等待的线程来唤醒(通过调用notify()或notifyall()方法)。线程等待直到它再次获得对象的监视器所有权。

synchronized (obj) {
    while (<condition does not hold>)
    obj.wait();
 ... // perform action appropriate to condition
}

 4.  notify()

wakes up a single thread that is waiting on this object's monitor. if any threads are waiting on this object, one of them is chosen to be awakened. the choice is arbitrary and occurs at the discretion of the implementation. 

唤醒一个在对象的监视器等待的线程。如果有多个线程等待在该对象的监视器上,它们中的一个会被选中唤醒。这个选中是任意的,并且取决于具体实现。

5.  notifyall()

wakes up all threads that are waiting on this object's monitor.

唤醒在该对象的监视器上等待的所有线程