ProducerConsumer with wait, notify

Kategori: Java , 21 Temmuz 2019 , JanFranco


Bir önceki yazımızda wait ve notify methodlarını görmüştük. Bu yazımızda bu methodları kullanarak ProducerConsumer problemini tekrar ele alacağız. Kod üzerinden görelim:


import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

public class ProducerConsumer {
	
	Random random = new Random();
	Object lock = new Object();
	Queue<Integer> queue = new LinkedList<Integer>();
	private int limit = 10;

	public void producer(){
		
		while(true){
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("Producer Interrupted.");
			}
			
			synchronized (lock) {
				
				if(queue.size() == limit){
					
					try {
						System.out.println("Producer will sleep...");
						lock.wait();
					} catch (InterruptedException e) {
						System.out.println("Lock interrupted...");
					}
					
				}
				
				int value = random.nextInt(100);
				queue.offer(value);
				System.out.println("Producing: " + value);
				lock.notify();
				
			}
			
		}
		
	}
	
	public void consumer(){
		
		while(true){
			
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e1) {
				System.out.println("Sleeping Interrupted...");
			}
			
			synchronized (lock) {
				
				int value = queue.poll();
				System.out.println("Consuming: " + value);
				lock.notify();
				
			}
			
		}
		
		
	}
	
}
Burada eğer queue boyutu 10 olursa producer wait methodu ile duracak, ocnsumer bir ürün tüketecek ve notify methodu ile producer'ı tekrar uyandıracak. Threadleri oluşturup görelim:

public class Main_class {
	
	public static void main(String[] args){
		
		ProducerConsumer pc = new ProducerConsumer();
		
		Thread producer = new Thread(new Runnable() {
			
			@Override
			public void run() {
				pc.producer();
			}
		});
	
		Thread consumer = new Thread(new Runnable() {
			
			@Override
			public void run() {
				pc.consumer();
			}
		});
		
		producer.start();
		consumer.start();
		
		try {
			producer.join();
			consumer.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
Sonuç:

Producing: 35
Producing: 67
Consuming: 35
Producing: 17
Producing: 80
Producing: 81
Consuming: 67
Producing: 1
Producing: 97
Producing: 44
Consuming: 17
Producing: 48
Producing: 30
Producing: 98
Consuming: 80
Producing: 28
Producing: 44
Producing: 86
Consuming: 81
Producing: 24
Producer will sleep...
Consuming: 1
Producing: 17
Producer will sleep...
Consuming: 97
Producing: 0
Producer will sleep...
Consuming: 44
Producing: 90
Producer will sleep...
Consuming: 48
Producing: 80
Producer will sleep...
Consuming: 30
Producing: 75
Producer will sleep...


Sonraki Yazı: ReentrantLock, Condition Class, await, signal
Yorumlar

Henüz bir yorum bulunmuyor.
Yorum bırakın