Created
September 6, 2014 16:38
-
-
Save marinhoarthur/23bbdb3b3912f10cf9a5 to your computer and use it in GitHub Desktop.
Producer-Consumer problem with Threads
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
class Even extends Thread | |
{ | |
Holder h; | |
Even(Holder h) | |
{ | |
this.h = h; | |
} | |
public void run() | |
{ | |
while(true) | |
{ | |
synchronized (h) | |
{ | |
h.i++; | |
System.out.println(getName() + " " + h.i); | |
try | |
{ | |
Thread.sleep(1000); | |
h.notify(); | |
h.wait(); | |
} | |
catch (InterruptedException e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
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
class Holder | |
{ | |
int i; | |
} |
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
class Odd extends Thread | |
{ | |
Holder h; | |
Odd(Holder h) | |
{ | |
this.h = h; | |
} | |
public void run() | |
{ | |
while(true) | |
{ | |
synchronized (h) | |
{ | |
h.i++; | |
System.out.println(getName() + " " + h.i); | |
try | |
{ | |
h.notify(); | |
h.wait(); | |
} | |
catch (InterruptedException e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
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
public class OddEvenProducerConsumerThread | |
{ | |
public static void main(String[] args) throws InterruptedException | |
{ | |
Holder h = new Holder(); | |
Thread o = new Odd(h); | |
Thread e = new Even(h); | |
o.setName("Odd"); | |
e.setName("Even"); | |
o.start(); | |
Thread.sleep(200); // give o time to start and enter into waiting state | |
e.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment