Skip to content

Instantly share code, notes, and snippets.

@marinhoarthur
Created September 6, 2014 16:38
Show Gist options
  • Save marinhoarthur/23bbdb3b3912f10cf9a5 to your computer and use it in GitHub Desktop.
Save marinhoarthur/23bbdb3b3912f10cf9a5 to your computer and use it in GitHub Desktop.
Producer-Consumer problem with Threads
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();
}
}
}
}
}
class Holder
{
int i;
}
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();
}
}
}
}
}
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