Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author Jakub
- */
- public class MyThread {
- public static void main(String[] args)throws InterruptedException {
- final PC pc = new PC();
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run()
- {
- try {
- pc.produce();
- } catch (InterruptedException ex) {
- System.out.println(ex);
- }
- }
- });
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run()
- {
- try {
- pc.consume();
- } catch (InterruptedException ex) {
- System.out.println(ex);
- }
- }
- });
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- }
- public static class PC {
- LinkedList<Integer> list = new LinkedList<>();
- int capacity = 2;
- public void produce() throws InterruptedException
- {
- int value = 0;
- while (true) {
- synchronized (this)
- {
- while (list.size() == capacity)
- wait();
- list.add(value++);
- notify();
- }
- }
- }
- public void consume() throws InterruptedException
- {
- while (true) {
- synchronized (this)
- {
- while (list.size() == 0)
- wait();
- list.removeFirst();
- notify();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement