Created
November 3, 2012 14:08
-
-
Save yssharma/4007474 to your computer and use it in GitHub Desktop.
A threaded producer consumer class (Confused Coders)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** The Resource Class - The root cause of all fight **/ | |
class Resource { | |
private Boolean isProduced = false; | |
private String data = "EMPTY"; | |
/** Put method : puts only if is not already produced **/ | |
public synchronized void put(String data) throws InterruptedException { | |
if (isProduced) { | |
wait(); // Not Consumed Yet,Wait for consumer's signal. | |
} else { | |
this.data = data; | |
isProduced = true; | |
notify(); // Tell the Consumer that i'm done producing. | |
System.out.println("Producer >> Data:" + this.data); | |
} | |
} | |
/** Get method : gets only if it has been produced **/ | |
public synchronized String get() throws InterruptedException { | |
if (!isProduced) { | |
wait(); // Not produced yet,wait for producer's signal. | |
} else { | |
String data = this.data; | |
this.data = "EMPTY"; | |
isProduced = false; | |
notify(); // Tell the Producer that i'm done consuming. | |
System.out.println("Consumer >> Data:" + this.data); | |
return data; | |
} | |
return data; | |
} | |
} | |
/** The Produver Thread **/ | |
class ProducerThread implements Runnable { | |
Resource resource; | |
public void run() { | |
for (int i = 0; i < 50; i++) { | |
try { | |
resource.put("DATA ADDED"); | |
} catch (InterruptedException e) { | |
} | |
} | |
} | |
public ProducerThread(Resource resource) { | |
this.resource = resource; | |
new Thread(this).start(); | |
} | |
} | |
/** The Consumer Thread **/ | |
class ConsumerThread implements Runnable { | |
Resource resource; | |
public void run() { | |
for (int i = 0; i < 50; i++) { | |
try { | |
resource.get(); | |
} catch (InterruptedException ex) { | |
} | |
} | |
} | |
public ConsumerThread(Resource resource) { | |
this.resource = resource; | |
new Thread(this).start(); | |
} | |
} | |
/** Test Class **/ | |
public class ProducerConsumer { | |
public static void main(String[] args) { | |
Resource resource = new Resource(); | |
new ProducerThread(resource); | |
new ConsumerThread(resource); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment