Last active
December 14, 2015 12:39
-
-
Save lobster1234/5087835 to your computer and use it in GitHub Desktop.
Producer Consumer - Inefficient (sleep) implementation. Prone to deadlocks.
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
import java.util.Stack; | |
public class Bucket { | |
private Stack<Long> stack = new Stack<Long>(); | |
private int MAX_SIZE = 20; | |
public Long consume(){ | |
return stack.pop(); | |
} | |
public void produce(Long l){ | |
stack.push(l); | |
} | |
public boolean isEmpty(){ | |
return stack.isEmpty(); | |
} | |
public boolean isFull(){ | |
return stack.size()==MAX_SIZE; | |
} | |
public static void main(String[] args) throws Exception{ | |
Bucket bucket = new Bucket(); | |
Thread producer1 = new Thread(new Producer(bucket,"Producer1")); | |
Thread consumer1 = new Thread(new Consumer(bucket,"Consumer1")); | |
Thread producer2 = new Thread(new Producer(bucket,"Producer2")); | |
producer1.start(); | |
producer2.start(); | |
consumer1.start(); | |
producer1.join(); | |
producer2.join(); | |
consumer1.join(); | |
} | |
} | |
class Producer implements Runnable{ | |
private Bucket b; | |
private String name; | |
public Producer(Bucket b, String name){ | |
this.b = b; | |
this.name = name; | |
} | |
public void run(){ | |
while(true){ | |
try{ | |
if(!b.isFull()) { | |
b.produce(System.nanoTime()); | |
} | |
else { | |
System.out.println("Bucket full - Producer " + name + " sleeping"); | |
Thread.sleep(500); | |
} | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
class Consumer implements Runnable{ | |
private Bucket b; | |
private String name; | |
public Consumer(Bucket b, String name){ | |
this.b = b; | |
this.name = name; | |
} | |
public void run(){ | |
while(true){ | |
try{ | |
if(!b.isEmpty()) b.consume(); | |
else { | |
System.out.println("Bucket Empty - Consumer " + name + " sleeping.."); | |
Thread.sleep(500); | |
} | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment