Package Xiancheng;
/**
* Wait () Waits, release lock sleep does not release lock
* @author User
*
*/
public class Lianxi20 {
T producer production notice consumption F consumer consumption notice production
Private Boolean flag=true;
Simulation of the production of goods
Private String picstring;
Production
Public synchronized void Play (String picstring) {
When flag is false, the producer stops working and enters the waiting state
if (!flag) {
try {
This.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
Simulate production time
try {
Thread.Sleep (200);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Execution of production
this.picstring=picstring;
Notification consumption
This.notifyall ();
Producer Stop
This.flag=false;
}
Consumption
public synchronized Void Watch () {
When flag is true the consumer stops waiting to enter the waiting state
if (flag) {
try {
This.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
Simulating the consumption process
try {
Thread.Sleep (500);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Conduct consumer operations
System.out.println (picstring);
Notify production
This.notify ();
Consumer Stop
This.flag=true;
}
}
/**
* Producer
* @author User
*
*/
public class LIANXI21 implements runnable{
Defining resources
Private lianxi20 m;
Defining a parameter-containing constructor
Public lianxi21 (lianxi20 m) {
THIS.M = m;
}
To override the Run method for production operations
@Override
public void Run () {
for (int i=0;i<20;i++) {
if (0==i%2) {
M.play ("silly light");
}else {
M.play ("Spring");
}
}
}
}
/**
* Consumer
* @author User
*
*/
public class Lianxi22 implements runnable{
Defining resources
Private lianxi20 m;
Defining a parameter-containing constructor
Public lianxi22 (lianxi20 m) {
THIS.M = m;
}
Override the Run method, and thread execution is a watch operation
@Override
public void Run () {
for (int i=0;i<20;i++) {
M.watch ();
}
}
}
public class Lianxi23 {
public static void Main (string[] args) {
Common resources
Lianxi20 m=new lianxi20 ();
Define Producer
Lianxi21 p=new lianxi21 (m);
Define Producer
Lianxi22 w=new lianxi22 (m);
Thread to
New Thread (P). Start ();
New Thread (W). Start ();
}
}
Implement multi-threaded sequential execution issues by addressing producer consumer issues.
Producer consumer issues with threads