> Java > java지도 시간 > 본문

Java 동시성에서 스레드 간 협력을 위한 두 가지 방법: wait, inform, informAll 및 Condition

黄舟
풀어 주다: 2017-03-18 10:09:08
원래의
1251명이 탐색했습니다.

스레드 간 협력. 예를 들어, 가장 고전적인 생산자-소비자 모델: 대기열이 가득 차면 생산자는 대기열에 상품을 계속 넣기 전에 대기열에 공간이 생길 때까지 기다려야 합니다. 대기 기간 동안 생산자는 중요한 리소스를 해제해야 합니다. 즉, 대기열) 점유 오른쪽. 생산자가 중요한 자원을 점유할 권리를 해제하지 않으면 소비자는 대기열에 있는 상품을 소비할 수 없으며 대기열에 공간이 없어지고 생산자는 무한정 기다리게 됩니다. 따라서 정상적인 상황에서는 대기열이 가득 차면 생산자에게 중요한 리소스를 점유할 수 있는 권한을 넘겨주고 일시 중지 상태로 들어가도록 요청하게 됩니다. 그런 다음 소비자가 상품을 소비할 때까지 기다린 다음 소비자는 대기열에 공간이 있음을 생산자에게 알립니다. 마찬가지로, 대기열이 비어 있으면 소비자는 생산자가 대기열에 항목이 있음을 알릴 때까지 기다려야 합니다. 이러한 상호 소통의 과정은 스레드 간의 협력입니다.

wait(), inform() 및 informAll()

[code]/**
 * 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. A thread waits on an object's
 * monitor by calling one of the wait methods
 */
public final native void notify();

/**
 * Wakes up all threads that are waiting on this object's monitor. A
 * thread waits on an object's monitor by calling one of the
 * wait methods.
 */
public final native void notifyAll();

/**
 * Causes the current thread to wait until either another thread invokes the
 * {@link java.lang.Object#notify()} method or the
 * {@link java.lang.Object#notifyAll()} method for this object, or a
 * specified amount of time has elapsed.
 * <p>
 * The current thread must own this object&#39;s monitor.
 */
public final native void wait(long timeout) throws InterruptedException;
로그인 후 복사

1) wait(), inform() 및 informAll() 메소드 이는 로컬 메서드이며 최종적이며 재정의할 수 없습니다.
2) 객체의 wait() 메소드를 호출하면 현재 스레드를 차단할 수 있으며, 현재 스레드는 이 객체의 모니터(즉, 잠금)를 소유해야 합니다.
3) 객체의 inform() 메소드를 호출하면 wake up an object 이 객체의 모니터를 기다리고 있는 스레드입니다. 이 객체의 모니터를 기다리는 스레드가 여러 개인 경우 그 중 하나만 깨울 수 있습니다.
4) informAll() 메서드를 호출하면 깨어날 수 있습니다. Thread;
어떤 친구들은 왜 이 세 가지가 Thread 클래스에 선언된 메서드가 아니고 Object 클래스에 선언된 메서드인지 궁금해할 수 있습니다. Object 클래스, Thread는 세 가지 메소드를 호출할 수도 있습니다)? 사실 이 문제는 매우 간단합니다. 각 개체에는 모니터(즉, 잠금)가 있으므로 현재 스레드가 개체의 잠금을 기다리는 경우 당연히 이 개체를 통해 작동해야 합니다. 현재 스레드를 사용하여 작업하는 대신 현재 스레드가 여러 스레드의 잠금을 기다리고 있을 수 있으므로 스레드를 통해 작업하는 것은 매우 복잡합니다.
위에서 언급한 것처럼 객체의 wait() 메서드가 호출되면 현재 스레드는 이 객체의 모니터(즉, 잠금)를 소유해야 하므로 wait() 메서드 호출은 동기화된 블록이나 동기화된 블록에서 이루어져야 합니다. 방법(동기화된 블록 또는 동기화된 방법).
개체의 wait() 메서드를 호출하는 것은 현재 스레드에 이 개체의 모니터를 넘겨달라고 요청한 다음 대기 상태로 들어가서 이 개체의 후속 잠금 획득을 다시 기다리는 것과 같습니다(sleep Thread 클래스의 메서드는 현재 스레드의 실행을 일시 중지하여 다른 스레드가 계속 실행할 수 있는 기회를 주지만 개체 잠금을 해제하지는 않습니다.
통지() 메서드는 스레드를 깨울 수 있습니다. 개체의 모니터를 기다리는 스레드, 여러 스레드가 개체를 기다리는 경우 모니터를 사용하면 스레드 중 하나만 깨울 수 있으며 깨울 특정 스레드를 알 수 없습니다.
마찬가지로 객체의 inform() 메서드를 호출할 때 현재 스레드도 이 객체의 모니터를 소유해야 하므로, inform() 메서드 호출은 동기화된 블록이나 동기화된 메서드(동기화된 블록 또는 동기화된 메서드)에서 이루어져야 합니다. 방법).
nofityAll() 메소드는 inform() 메소드와 달리 객체의 모니터를 기다리고 있는 모든 스레드를 깨울 수 있습니다.
여기서 주의할 점: inform() 및 informAll() 메소드는 객체의 모니터를 기다리고 있는 스레드만 깨울 뿐이며 어떤 스레드가 모니터를 얻을 수 있는지 결정하지 않습니다.
간단한 예를 들어 보겠습니다. Thread1, Thread2 및 Thread3 세 개가 모두 objectA의 모니터를 기다리고 있다고 가정합니다. 이때 objectA.notify() 메서드가 호출된 후 Thread4가 개체의 모니터를 소유합니다. Thread4, Thread1, Thread2와 Thread3 중 하나만 깨울 수 있습니다. 깨어난다고 해서 objectA의 모니터가 즉시 획득된다는 의미는 아닙니다. Thread4에서 objectA.notifyAll() 메서드가 호출되면 Thread1, Thread2 및 Thread3 세 스레드가 활성화됩니다. 다음에 objectA의 모니터를 얻을 수 있는 스레드는 운영 체제의 스케줄링에 따라 다릅니다.
위 사항에 특별히 주의하세요. 스레드가 깨어났다고 해서 즉시 개체의 모니터를 얻은 것은 아닙니다. 단지 inform() 또는 informAll()을 호출하고 동기화된 블록을 종료하고 개체 잠금을 해제한 후에만 가능합니다. 다른 스레드가 실행을 위해 잠금을 얻을 수 있습니까?

[code]public class Test {
    public static Object object = new Object();
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();

        thread1.start();

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        thread2.start();
    }

    static class Thread1 extends Thread{
        @Override
        public void run() {
            synchronized (object) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                }
                System.out.println("线程"+Thread.currentThread().getName()+"获取到了锁");
            }
        }
    }

    static class Thread2 extends Thread{
        @Override
        public void run() {
            synchronized (object) {
                object.notify();
                System.out.println("线程"+Thread.currentThread().getName()+"调用了object.notify()");
            }
            System.out.println("线程"+Thread.currentThread().getName()+"释放了锁");
        }
    }
}
로그인 후 복사

조건

조건은 Java 1.5에서만 나타났습니다. 이는 기존 객체의 wait(), inform( )을 대체하여 달성하는 데 사용됩니다. 스레드 간 협업 Object의 wait() 및 inform()을 사용하는 것과 비교할 때 Condition1의 wait() 및 signal()을 사용하여 스레드 간 협업을 수행하는 것이 더 안전하고 효율적입니다. 따라서 일반적으로 Condition을 사용하는 것이 좋습니다
Condition은 인터페이스이며 기본 메소드는 wait() 및 signal() 메소드입니다.
Condition은 Lock 인터페이스에 따라 다르며 Condition을 생성하는 기본 코드는 다음과 같습니다. lock.newCondition()
호출 조건의 wait() 및 signal() 메서드는 잠금 보호 내에 있어야 합니다. 즉, lock.lock()과 lock.unlock 사이에 사용해야 합니다.

Conditon中的await()对应Object的wait();
  Condition中的signal()对应Object的notify();
  Condition中的signalAll()对应Object的notifyAll()。
로그인 후 복사
[code]public class Test {
    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);

    public static void main(String[] args)  {
        Test test = new Test();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();

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

    class Consumer extends Thread{

        @Override
        public void run() {
            consume();
        }

        private void consume() {
            while(true){
                synchronized (queue) {
                    while(queue.size() == 0){
                        try {
                            System.out.println("队列空,等待数据");
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            queue.notify();
                        }
                    }
                    queue.poll();          //每次移走队首元素
                    queue.notify();
                    System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
                }
            }
        }
    }

    class Producer extends Thread{

        @Override
        public void run() {
            produce();
        }

        private void produce() {
            while(true){
                synchronized (queue) {
                    while(queue.size() == queueSize){
                        try {
                            System.out.println("队列满,等待有空余空间");
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            queue.notify();
                        }
                    }
                    queue.offer(1);        //每次插入一个元素
                    queue.notify();
                    System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
                }
            }
        }
    }
}
로그인 후 복사
[code]public class Test {
    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public static void main(String[] args)  {
        Test test = new Test();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();

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

    class Consumer extends Thread{

        @Override
        public void run() {
            consume();
        }

        private void consume() {
            while(true){
                lock.lock();
                try {
                    while(queue.size() == 0){
                        try {
                            System.out.println("队列空,等待数据");
                            notEmpty.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.poll();                //每次移走队首元素
                    notFull.signal();
                    System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
                } finally{
                    lock.unlock();
                }
            }
        }
    }

    class Producer extends Thread{

        @Override
        public void run() {
            produce();
        }

        private void produce() {
            while(true){
                lock.lock();
                try {
                    while(queue.size() == queueSize){
                        try {
                            System.out.println("队列满,等待有空余空间");
                            notFull.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.offer(1);        //每次插入一个元素
                    notEmpty.signal();
                    System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
                } finally{
                    lock.unlock();
                }
            }
        }
    }
}
로그인 후 복사

以上就是java-并发-线程间协作的两种方式:wait、notify、notifyAll和Condition的内容,更多相关内容请关注PHP中文网(www.php.cn)!

相关文章:

java notify和notifyAll的对比详细介绍

wait, notify 和 notifyAll的正确用法

通过实例讨论notify()和notifyAll()的本质区别

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!