Java simulated producer consumer issues
Java simulated producer consumer issues
I. Syncronized
To solve the problem of producer consumption, first take a look at the syncronized keyword in Java.
The synchronized keyword is used to protect shared data. Please pay attention to sharing data. You must distinguish which data is shared data. For example, the synchronized keyword in the following program does not protect shared data (in fact, the synchronized keyword in this program does not play any role, the running result of this program is uncertain ). T1 and t2 in this program are the threads of two objects (pp1, pp2. JAVA is an object-oriented programming language. The data of different objects is different. pp1 and pp2 have their own run () methods, while synchronized enables multiple threads of the same object, at a certain time point, only one thread can access the synchronized data of this object. Each object has a lock flag. When a thread of this object accesses a synchronized data of this object, all the data modified by synchronized of this object will be locked (because the lock mark is taken away by the current thread), only when the current thread has accessed the synchronized data to be accessed, the current thread releases the lock flag so that other threads of the same object have the opportunity to access synchronized data.
PackageSyncronizedMenthodTest;
ImportJava. io. File;
Import Java. io. FileNotFoundException;
ImportJava. io. IOException;
ImportJava. io. PrintStream;
Public classPrintProgramImplementsRunnable {
Public synchronized voidShow (){
PrintStreamps =Null;
Try{
Ps =NewPrintStream (NewFile(Test.txt ));
For(IntI = 0; I <100; I ++ ){
Ps. append (this is + Thread.CurrentThread(). GetName () + output + I + );
}
}Catch(IOException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Finally{
Ps. close ();
}
}
@ Override
Public voidRun (){
Show ();
}
Public static voidMain (String [] args ){
PrintProgrampp1 =NewPrintProgram ();
PrintProgrampp2 =NewPrintProgram ();
Threadt1 =NewThread (pp1 );
T1.setName (thread 1 );
Threadt2 =NewThread (pp2 );
T2.setName (thread 2 );
T1.start ();
T2.start ();
}
}
The content in test.txt is:
However, if the code is changed to the following code, the result will be different:
PackageSyncronizedMenthodTest;
ImportJava. io. File;
Import Java. io. FileNotFoundException;
ImportJava. io. IOException;
ImportJava. io. PrintStream;
Public classPrintProgramImplementsRunnable {
Public synchronized voidShow (){
PrintStreamps =Null;
Try{
Ps =NewPrintStream (NewFile(Test.txt ));
For(IntI = 0; I <100; I ++ ){
Ps. append (this is + Thread.CurrentThread(). GetName () + output + I
+ );
}
}Catch(IOException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Finally{
Ps. close ();
}
}
@ Override
Public voidRun (){
Show ();
}
Public static voidMain (String [] args ){
PrintProgrampp1 =NewPrintProgram ();
Threadt1 =NewThread (pp1 );
T1.setName (thread 1 );
T1.start ();
Threadt2 =NewThread (pp1 );
T2.setName (thread 2 );
T2.start ();
}
}
The result is as follows:
Because synchronized protects shared data. T1 and t2 are two threads of the same object (pp1). When one of the threads (for example, t2) executes the run () method, because run () is protected by synchronized, therefore, other threads (t1) of the same object cannot access the synchronized Method (run method ). T1 can be executed only after T2.
Ii. Simulate producer consumer issues in Java
After learning about the syncronized keyword in Java, the producer and consumer problems can also be solved. Example:
Solution:
--------------- <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + svrGtzwvcD4KPHA + LS0tLS0tLS0tLS0tLS0tPC9wPgo8cCBhbGlnbj0 = "left"> PackageProducerAndConsumerProblem;
Public classProduce {
/*
* Products produced by the producer
*/
PrivateString name;
Private doublePrice;
@ Override
PublicString toString (){
ReturnProduce [name = + name +, price = + price +];
}
PublicProduce (String name,DoublePrice ){
Super();
This. Name = name;
This. Price = price;
}
PublicProduce (){
Super();
}
PublicString getName (){
ReturnName;
}
Public voidSetName (String name ){
This. Name = name;
}
Public doubleGetPrice (){
ReturnPrice;
}
Public voidSetPrice (DoublePrice ){
This. Price = price;
}
}
---------------
Clerk
---------------
PackageProducerAndConsumerProblem;
Public classClerk {
// The clerk can store up to 20 products produced by the producer.
// Equivalent to a buffer zone
Static final intN= 20;
Private staticProduce []Produce=NewProduce [N];
Private static int ProduceNumber= 0;
Static int InIndex= 0;
Static int OutIndex= 0;
Private staticObjectObj=NewObject ();
Public staticProduce getProduce (IntIndex ){
Return Produce[Index];
}
Public static voidSetProduce (Produce produce,IntIndex ){
Clerk.Produce[Index] = produce;
}
Public staticObject getObj (){
Return Obj;
}
Public static voidSetObj (Object obj ){
Clerk.Obj= Obj;
}
Public synchronized voidAddProduce (){
If(ProduceNumber> = 20 ){
Try{
Wait ();
}Catch(InterruptedException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
}Else{
System.Out. Println (Thread.CurrentThread(). GetName ()
+ A product is produced and stored as a clerk +InIndex+ There );
Produceproduce =NewProduce ();
Clerk.SetProduce(Produce,InIndex);
InIndex= (InIndex+ 1) %N;
ProduceNumber++;
Policyall ();
}
}
Public synchronized voidGetProduce (){
If(ProduceNumber<= 0 ){
Try{
Wait ();
}Catch(InterruptedException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
}Else{
System.Out. Println (Thread.CurrentThread(). GetName () + slave
+OutIndex+ Clerk a commodity is taken from the store );
Clerk.SetProduce(Null,OutIndex);
OutIndex= (OutIndex+ 1) %N;
ProduceNumber--;
Policyall ();
}
}
}
---------------
Producer
---------------
PackageProducerAndConsumerProblem;
Public classProducerImplementsRunnable {
Clerkclerk =Null;
PublicProducer (Clerk clerk ){
This. Clerk = clerk;
}
@ Override
Public voidRun (){
While(True){
Try{
Thread.Sleep(1000 );
}Catch(InterruptedException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
Clerk. addProduce ();
}
}
}
---------------
Consumer
---------------
PackageProducerAndConsumerProblem;
Public classConsumerImplementsRunnable {
Clerkclerk =Null;
PublicConsumer (Clerk clerk ){
This. Clerk = clerk;
}
@ Override
Public voidRun (){
While(True){
Try{
Thread.Sleep(1000 );
}Catch(InterruptedException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
Clerk. getProduce ();
}
}
}
---------------
Main Function
---------------
PackageProducerAndConsumerProblem;
Public classTest {
Public static voidMain (String [] args ){
Clerkclerk =NewClerk ();
Consumerconsumer =NewConsumer (clerk );
Threadt1 =NewThread (consumer );
T1.setName (consumer );
Producerproducer =NewProducer (clerk );
Threadt2 =NewThread (producer );
T2.setName (producer );
T1.start ();
T2.start ();
}
}
---------------