Multithreading _ conveyor belt-How far can we go series (6)

Source: Internet
Author: User
Tags thread logic

 

How far can we go series (6)

It seems like an arrow, and I have reached the age of blind dates.

I have already begun preparing to move forward to the maturity stage of my life, just like an apple. From green apple to maturity, I have to go through a lot and face a lot, every friend around me has your credit.

Come on, everybody. We are not alone.

----------------------------------------------------------------

Java multithreading:
We have to remember about the synchronization method:
1. The thread is on an object. Two threads cannot call two different Synchronization Methods.
2. When a synchronous method has been executed, other threads can still call the non-synchronous method of this object.

In selvlet, to improve the response speed, a servlet is instantiated during initialization and then put into a map. When the response is required, the instance can be taken out of the map directly, this improves the response time when the same servlet is called repeatedly.
The servlet itself is multi-threaded. when calling the same servlet, it adopts the thread pool method. (For the thread pool, for Tomcat, you can use the <connector> element in server. XM to set the number of thread pools)
Therefore, Servlet users should understand that servlet is thread-safe.

The following methods are recommended to avoid non-security issues:
1. If singlethread is used, the servlet version is obsolete and can be ignored.
2. Synchronize and share data for multiple threads.
3. Do not use instance variables or static variables

 
Static variables are non-secure instance variables. In Singleton mode, local variables are thread-safe.

----------------------------------------

The essence of multi-threaded control should be to control shared data to control multi-threaded logic.

Two threads execute tasks in turn:

MasterProgram:

Public ClassMaintest {Public Static VoidMain (string [] ARGs) {flgclass=NewFlgclass ();//Shared data//Two threadsThread T1 =NewThread (NewThread1 (flgclass); thread T2=NewThread (NewThread2 (flgclass); t1.start (); t2.start ();}}

Shared data:

//Shared dataPublic ClassFlgclass {Private BooleanFlg;Public BooleanIsflg (){ReturnFlg ;}Public VoidSetflg (BooleanFlg ){This. Flg =Flg ;}}

Two threads:

 Public  Class Thread1 Implements  Runnable {  Private  Flgclass; thread1 (flgclass ){  This . Flgclass = Flgclass ;}  Public   Void  Run (){  Int I = 5 ;  Synchronized  (Flgclass ){ //  In a loop              While (I> 0 )  If  (Flgclass. isflg () {system. Out. println (thread. currentthread (). getname () + "" + I); flgclass. setflg (  False ); //  Control shared data to control thread Logic  Flgclass. Y (); -- I ;} Else  {  Try  {Flgclass. Wait ();}  Catch  (Interruptedexception e) {e. printstacktrace ();}}}}} 
 Public   Class Thread2 Implements  Runnable {  Private  Flgclass; thread2 (flgclass ){ This . Flgclass = Flgclass ;}  Public   Void  Run (){  Int I = 5 ;  Synchronized  (Flgclass ){  While (I> 0 )  If (! Flgclass. isflg () {system. Out. println (thread. currentthread (). getname () + "" + I); flgclass. setflg (  True  ); Flgclass. Policy (); -- I ;}  Else  {  Try  {Flgclass. Wait ();}  Catch  (Interruptedexception e) {e. printstacktrace ();}}}}} 

 

About thread pool:

//Create a thread pool that can reuse a fixed number of threadsExecutorservice pool = executors. newfixedthreadpool (2 );
 
//Create a thread pool that can be scheduled to run commands or periodically after a given delay.Scheduledexecutorservice pool = executors. newscheduledthreadpool (2 );
 
//Create a waiting queueBlockingqueue bqueue =NewArrayblockingqueue (20);//Create a single-threaded execution program that can be scheduled to run commands or regularly after a given delay.Threadpoolexecutor pool =NewThreadpoolexecutor (2, 3, 2, timeunit. milliseconds, bqueue );

 

Division of labor makes progress in modern society!

Now, the division of labor for a product is very fine. A worker only needs to do one thing well. For example, after manufacturing a mobile phone, a batch of workers only make mobile phone screens, and a batch of workers make shells, this improves production efficiency.

I think of the workflow on the conveyor belt: After a worker weld a point, the product will be passed down. The next worker welds another point and knows that the last worker gets the finished product and only needs to pack it.

When chatting with his predecessors, he said that most programs such as network interaction work like this.

So I want to learn a simple process model.

Implementation:

Product Type:

 /**  ** The simplified product class is used as the shared data and is the operation object of the thread logic.  */  Public   Class  Product {  //  Product NO.      Private  Int  ID;  //  Use state to view the stage of the Product      Private   Int  State; product (  Int ID, Int  State ){  This . ID = ID;  This . State = State ;}  Public  Int  GETID (){  Return  ID ;}  Public   Void Setid ( Int  ID ){  This . ID = ID ;}  Public   Int  Getstate (){  Return  State ;} Public   Void Setstate ( Int  State ){  This . State = State ;}} 

Main function:

 Import  Java. util. Concurrent. executorservice;  Import  Java. util. Concurrent. executors;  Public   Class  Pooltest {  Public  Static   Void  Main (string [] ARGs ){  //  Create a thread pool with reusable fixed threads (producer thread pool) Executorservice producerpool = executors. newfixedthreadpool (3 );  //  Wrapper thread pool (there are three wrapper workers) Executorservice packerpool = executors. newfixedthreadpool (3 );  //  5 product operations required Product p1 = New Product (1, 1); Product p2 = New Product (2, 1 ); Product p3 = New Product (3, 1 ); Product p4 = New Product (4, 1 ); Product P5 = New Product (5, 1 );  //  5 production workers are required Producerpool.exe cute ( New Producer (P1); producerpool.exe cute (  New  Producer (P2); producerpool.exe cute (  New  Producer (P3); producerpool.exe cute (  New  Producer (P4); producerpool.exe cute (  New  Producer (P5 ));  //  5 wrapper workers are required Packerpool.exe cute ( New  Packer (P1); packerpool.exe cute ( New  Packer (P2); packerpool.exe cute (  New  Packer (P3); packerpool.exe cute (  New  Packer (P4); packerpool.exe cute (  New  Packer (P5 ));  //  Disable Thread Pool Producerpool. Shutdown (); //  I think we should check whether all threads in this pool are released during shutdown.  Packerpool. Shutdown ();}} 

Production thread:

Public   Class Producer Extends  Thread {  Private  Product product; Producer (product ){  This . Product = Product;} @ override  Public   Void  Run (){  Synchronized  (Product ){  While (True  ){  If (Product. getstate () = 1 ) {System. Out. println (product. GETID () + "Number --- entering the production stage ---" );  Try  {Product. setstate ( 2 ); //  Mark next stage Sleep (500 ); System. Out. println (product. GETID () + "No. --- Production completed ---" ); Product. Policy (); //  Releasing resources is equivalent to sending the produced products to the next operator --> Packaging } Catch  (Interruptedexception e) {e. printstacktrace ();}}  Else   If (Product. getstate ()> 1 ){ //  It is in the next stage                      Break ; //  Release thread } Else { // Before the production stage                      Try  {Product. Wait ();  //  The product cannot enter the production stage } Catch  (Interruptedexception e) {e. printstacktrace ();}}}}}} 

Packaging thread:

 Public   Class Packer Extends  Thread {  Private Product product; packer (product ){  This . Product = Product;} @ override  Public   Void  Run (){  Synchronized  (Product ){  While ( True  ){  If (Product. getstate () = 2 ) {System. Out. println (product. GETID () + "Number --- entering the packaging stage ---" );  Try  {Product. setstate ( 3 ); //  Mark next stage Sleep (100 ); System. Out. println (product. GETID () + "No. --- packed ---" ); Product. Policy ();  //  Releasing resources is equivalent to sending packaged products to the next stage. } Catch (Interruptedexception e) {e. printstacktrace ();}}  Else   If (Product. getstate ()> 2 ){ //  It is in the next stage                      Break ; //  Release thread } Else { //  Before the packaging phase                      Try  {Product. Wait (); //  The product cannot enter the packaging stage } Catch  (Interruptedexception e) {e. printstacktrace ();}}}}}} 

 

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.
Mutual encouragement.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.