Package com.cn.thread;
Import java.util.ArrayList;
Import java.util.List;
/**
* Simulating producer consumption patterns
* @author Johnzhang
*
*/
public class Waitandnotifymain {
public static void Main (string[] args) {
Waitandnotify waitandnotify = new Waitandnotify ();
Runnable r1 = new Thread1 (waitandnotify);
Runnable r2 = new Thread2 (waitandnotify);
New Thread (R2). Start ();
New Thread (R1). Start ();
}
}
Class Thread1 implements Runnable {
Waitandnotify waitandnotify;
Public Thread1 (Waitandnotify waitandnotify) {
This.waitandnotify = waitandnotify;
}
@Override
public void Run () {
TODO auto-generated Method Stub
Waitandnotify.getlist ();
}
}
Class Thread2 implements Runnable {
Waitandnotify waitandnotify;
Public Thread2 (Waitandnotify waitandnotify) {
This.waitandnotify = waitandnotify;
}
@Override
public void Run () {
TODO auto-generated Method Stub
Waitandnotify.setlist ();
}
}
Class Waitandnotify {
private int size;
Private list<string> context;
Private Boolean isOK = false;
Public waitandnotify () {
This.size = 10;
context = new arraylist<string> ();
for (int i = 0; i < size; i++) {
Context.add ("value" + (i + 1));
// }
}
Public synchronized void setlist () {
try {
while (true) {
if (isOK) {
System.out.println ("Get it Done" + isOK);
This.wait ();
}else{
for (int i = 1; I <= size; i++) {
System.out.println ("To make a la la, make something: food" + i);
Context.add ("Food" + i);
Thread.Sleep (500);
}
isOK = true;
This.notify ();
}
}
} catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}
}
Public synchronized void GetList () {
try {
while (true) {
if (!isok) {
SYSTEM.OUT.PRINTLN ("No food is forbidden for users to eat" + isOK);
This.wait ();
}else{
SYSTEM.OUT.PRINTLN ("Food users Eat" + isOK);
for (int i = 1; I <= size; i++) {
System.out.println ("To consume, the thing to consume is" + context.get (0) + "i =" + i + "context.size =" + context.size ());
System.out.println ("Context.value" + context.tostring ());
Context.remove (0);//Eat the first one at a time
Thread.Sleep (500);
System.out.println ("Return i=============== after Sleep" + i);
}
isOK = false;
This.notify ();
}
}
} catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}
}
}
Java-thread-producer consumption patterns