Take three class: Producer,Consumer and ProducerConsumerDemo.
Here ProducerConsumerDemo is main class.
Code:
Here ProducerConsumerDemo is main class.
Code:
- import java.util.ArrayList;
- public class Producer implements Runnable {
- private ArrayList<Integer>list;
- public Producer(ArrayList<Integer>list) {
- // TODO Auto-generated constructor stub
- this.list=list;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- int count=1;
- while (count<=3) {
- synchronized (list) {
- list.add(count);
- System.out.println("Produced :: "+count);
- count++;
- try {
- list.notify();
- System.out.println("Notify the consumer.");
- list.wait();
- } catch (InterruptedException e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- }
- }
- }
- import java.awt.List;
- import java.util.ArrayList;
- public class Consumer implements Runnable {
- private ArrayList<Integer>list;
- public Consumer(ArrayList<Integer>list) {
- // TODO Auto-generated constructor stub
- this.list=list;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- int count=1;
- while (count<=3) {
- synchronized (list) {
- while (list.size()==0) {
- try {
- list.notify();
- System.out.println("Notify the producer: ");
- list.wait();
- } catch (InterruptedException e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- Integer value=list.remove(0);
- System.out.println("Consumed ::"+value);
- count++;
- try {
- list.notify();
- System.out.println("Notify the producer: ");
- list.wait();
- } catch (InterruptedException e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- }
- }
- }
- import java.util.ArrayList;
- public class ProducerConsumerDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- ArrayList<Integer>list=new ArrayList<Integer>();
- Thread t1=new Thread(new Producer(list));
- Thread t2=new Thread(new Consumer(list));
- t1.start();
- t2.start();
- }
- }
0 Comments:
Post a Comment