Saturday, 11 January 2014

Advanced Java_ Multi-threading Part 9 - A Worked Example Using Low-Level Synchronization


====
package Demo11;

/**
 * Title -- Advanced Java_ Multi-threading Part 9 - A Worked Example Using Low-Level Synchronization
 *
 * @author Dharmaraj.Net
 */
public class App {

 public static void main(String[] args) throws InterruptedException {
  final Processor processor = new Processor();

  Thread t1 = new Thread(new Runnable() {

   public void run() {
    try {
     processor.producer();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }

  });

  Thread t2 = new Thread(new Runnable() {

   public void run() {
    try {
     processor.consumer();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }

  });

  t1.start();
  t2.start();

  t1.join();
  t2.join();
 }

}
====
package Demo11;

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

public class Processor {

 private LinkedList<Integer> list = new LinkedList<Integer>();
 private final int LIMIT = 10;
 private Object lock = new Object();

 /**
  * This method is add items to the list
  * 
  * @throws InterruptedException
  */
 public void producer() throws InterruptedException {
  int value = 0;
  while (true) {

   synchronized (lock) {

    while (list.size() == LIMIT) {
     lock.wait();
    }

    list.add(value++);
    lock.notify();
   }
  }

 }

 /**
  * This method is remove items to the list
  * 
  * @throws InterruptedException
  */
 public void consumer() throws InterruptedException {
  Random random = new Random();
  while (true) {
   synchronized (lock) {
    while (list.size() == 0) {
     lock.wait();
    }
    System.out.println("List Size " + list.size());
    int value = list.removeFirst();
    System.out.println("Value is " + value);
    lock.notify();
   }
   Thread.sleep(random.nextInt(1000));
  }
 }
} 

No comments:

Post a Comment