Java Architecture "Concurrent Threading Advanced Chapter III"

Source: Internet
Author: User

This chapter mainly introduces and explains the common tool class in Concurrent.util.

One, Countdownlatch use: (for blocking the main thread)

Scenario: A tool class that notifies the thread to hibernate and run is an upgraded version of wait and notify. Notify does not release the lock, but countdown () releases the lock

Instantiation: Final Countdownlatch countdown = new Countdownlatch (2);

Used in thread: Countdownlatch.countdown (); equivalent to Notfiy; Countdown () Releases the lock
Countdownlatch.await (); equivalent to wait;

Second, cyclicbarrier use: Barrier (barrier) (for multiple blocking threads waiting, all ready to start executing the code of the current thread)

Scenario: Multiple threads are blocked when none of the threads are ready. When both are ready, execute their own threads.

Note: How many threads, how many barrier.await () are required, otherwise it will be blocked here.

Code parsing:

          

public class Usecyclicbarrier {

Static Class Runner implements Runnable {
Private Cyclicbarrier barrier;
private String name;

Public Runner (cyclicbarrier barrier, String name) {
This.barrier = barrier;
THIS.name = name;
}
@Override
public void Run () {
try {
Thread.Sleep (New Random ()). Nextint (5));
SYSTEM.OUT.PRINTLN (name + "ready OK.");
Barrier.await ();
} catch (Interruptedexception e) {
E.printstacktrace ();
} catch (Brokenbarrierexception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN (name + "go!!");
}
}

public static void Main (string[] args) throws IOException, Interruptedexception {
Cyclicbarrier barrier = new Cyclicbarrier (3); 3
Executorservice executor = Executors.newfixedthreadpool (3);

Executor.submit (New Thread (New Runner (barrier, "Zhangsan"));
Executor.submit (New Thread (New Runner (barrier, "Lisi"));
Executor.submit (New Thread (New Runner (barrier, "Wangwu"));

Executor.shutdown ();
}

}

Iii. replenishment and callable of the future model

Usage scenario: Asynchronously processes data to improve program throughput when large quantities of data are needed

Note: The class that truly handles the business logic, the class must implement the callable interface, overriding the call () method.

Private String para;

Public usefuture (String para) {
This.para = para;
}

/**
* Here is the real business logic, its execution may be slow
*/
@Override
Public String Call () throws Exception {
Time-consuming simulation execution
Thread.Sleep (5000);
String result = This.para + "Processing complete";
return result;
}

       

String querystr = "Query";
Constructs a futuretask, and passes in a class that needs to really do business logic, and that class must be the class that implements the callable interface
futuretask<string> future = new Futuretask<string> (new Usefuture (QUERYSTR));

futuretask<string> future2 = new futuretask<string> (new Usefuture (QUERYSTR));
Creates a thread pool of fixed threads with a thread count of 1.
Executorservice executor = Executors.newfixedthreadpool (2);
This commits the task to the future, then the call () method execution of the thread execution Realdata is turned on
The difference between the Submit and execute: The 1th is that submit can be passed to the instance object implementing the callable interface, and the 2nd is the return value of the Submit method

Future F1 = Executor.submit (future);//Start a thread alone to execute the
Future F2 = Executor.submit (Future2);
SYSTEM.OUT.PRINTLN ("request Complete");

try {
Additional data operations can be done here, i.e. the main program executes other business logic
System.out.println ("Dealing with the actual business logic ...");
Thread.Sleep (1000);
} catch (Exception e) {
E.printstacktrace ();
}
Called to get the data method, if the call () method does not complete, it will still wait
SYSTEM.OUT.PRINTLN ("Data:" + future.get ());
SYSTEM.OUT.PRINTLN ("Data:" + future2.get ());

Executor.shutdown ();

        

Summary: Futuretask object. When the Get () method is used, the corresponding return result is loaded asynchronously. Future objects. When you use its get () method. Returns NULL, indicating that the child thread has completed.

The difference between the Submit and execute: The 1th is that a submit can pass in an instance object that implements the callable interface, and the 2nd is the return value of the Submit method.

Iv. Semaphore Signal Volume

Usage scenario: Before the system goes live, the system is evaluated for the amount of information concurrency. for automated testing.

Related concepts:

PV (Page view): Total site visits, page views or clicks, recorded every refresh.

UV (Unique Visitor): The total number of IP sites visited, without an IP, recorded only once in a day.
QRS (query per second): The number of queries per second.

RT (response time): access the appropriate times.

        

               

            

      

Java Architecture "Concurrent Threading Advanced Chapter III"

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.