Java Distributed Application Study Notes 05 concurrent synchronization under multiple threads ---- previous

Source: Internet
Author: User

 

1. Preface

In addition to the Collection mentioned in the previous article, JDK also provides thread scheduling, collaboration, scheduling, and other functions. As mentioned in the previous article, in addition to competition and collaboration between threads. Special scenarios in which Java concurrent packages can be effectively used in high-concurrency environments to solve inter-thread collaboration. These concurrent syntaxes are used in parallel computing, especially when the result set of multi-thread computing is combined. Another application scenario is to perform parallel operations across multiple threads on multiple machines (real machines). You Need To summarize and merge the result sets of multiple machines. The core principle is to use these concurrent collaboration packages.

2. FutureTask

FutureTask is a class that combines parallel result sets. This class is the implementation of the Future interface. Start multiple threads in the main thread for concurrent computing, and then summarize and merge the results based on the execution results of each thread to get a general result. This multi-thread can be on one machine, taking full advantage of multi-core CPU hardware, a large task can be computed concurrently in a distributed cluster environment of a scientific research organization. Each machine is equivalent to a thread, the final result is returned after the execution is completed. The main thread can wait for the results of the sub-thread, or wait for it, depending on the specific business needs. However, it is generally necessary to wait for the results of the sub-thread to be executed. If the thread is not split, you can ignore the thread in the main thread.

Take an example. For example, if you want to become a "sunflower Collection", you need two prerequisites. The secret of "sunflower Collection" is obtained first, and the second is to play a sword in your house. Well, the main thread of the game-the invincible in the east can be done on its own, to win the "sunflower Collection" can be a faction-Brother Tong Bai Xiong to do the work, two lines of parallel implementation, when another person gets the "sunflower Collection", the main thread here will also throw the knife to his own palace. Now, I can practice it!

Let's take a look at the code first.

Java code

<Span style = "font-size: small;"> package threadConcurrent. test;

 

Import java. util. concurrent. Callable;

Import java. util. concurrent. ExecutionException;

Import java. util. concurrent. FutureTask;

 

/**

* Thread-specific summary

* @ Author liuyan

*/

Public class FutureTaskDemo {

 

@ SuppressWarnings ("unchecked ")

Public static void main (String [] args ){

 

// Initialize a Callable object and a FutureTask object

Callable otherPerson = new OtherPerson ();

 

// Execute this task

FutureTask futureTask = new FutureTask (otherPerson );

 

// Use futureTask to create a thread

Thread newhread = new Thread (futureTask );

System. out. println ("newhread thread starts now. Start Time:" + System. nanoTime ()

+ "Nanoseconds ");

Newhread. start ();

System. out. println ("main thread -- unbeaten in the east, start to execute other tasks ");

System. out. println ("Preparing a knife and disinfecting the knife in an unbeaten manner ...");

 

// Whether the computing thread of the sibling thread in the background is complete. If not, wait.

// Blocking

While (! FutureTask. isDone ()){

Try {

Thread. sleep (500 );

System. out. println ("invincible in the east:" when my brother returns, I will say goodbye to my younger brother ...... Trembling ......" ");

} Catch (InterruptedException e ){

E. printStackTrace ();

}

}

System. out. println ("newhread thread execution is completed, and the time is" + System. nanoTime ());

String result = null;

Try {

Result = (String) futureTask. get ();

 

} Catch (InterruptedException e ){

E. printStackTrace ();

} Catch (ExecutionException e ){

E. printStackTrace ();

}

If ("OtherPerson: after some kill, get the" sunflower Collection "". equals (result )){

System. out. println! ");

} Else {

System. out. println ("Okay, I'm not here! Otherwise, the sacrifice will be made in vain ...... ");

}

}

}

 

@ SuppressWarnings ("all ")

Class OtherPerson implements Callable {

 

@ Override

Public Object call () throws Exception {

 

// Rest and try again!

Thread. sleep (5000 );

String result = "OtherPerson: after some kill, you can get the sunflower Collection";

System. out. println (result );

Return result;

}

 

} </Span>

In this example, the main thread represents an undefeated job in the east, and the sub-thread represents the Brother Tong baixiong. The main thread sends FutureTask to place it in a thread object, and then the thread starts to start, the branch thread starts to work. The main thread is not idle, continue to do its own thing, disinfect, do psychological struggle, and so on, through a blocked endless loop, waiting for the status of sub-thread, call the sub-thread futureTask. the isDone () method is used to determine whether the execution of the sibling program is finished and the result is completed through futureTask. get () gets the execution result of the sub-thread and the result is displayed. The main thread makes a decision based on the execution result of the sub-thread. After the execution, the results are displayed. One thing to note is that it is possible that the thread and the main thread are not executed on a physical machine, threads can use jms, webservic, rmi, or even socket technology to Request Remote classes to serve them. The sub-thread returns the result to the main thread of the Machine Based on the remote return result, and then makes the decision. The core principle of distributed computing is also the same. Of course, distributed computing is much more complicated than this. I just want to talk about its core implementation principle.

3. Semaphore

Semaphore is a stuff that limits multi-thread Resource Sharing. When multi-thread accesses a resource concurrently, it can limit the maximum number of threads used. If there are other threads that come out, no way. Please wait. This example is everywhere in life. There are five windows in the ticket office of the railway station, which means that at the same time, the railway station staff can only serve up to five people, what about other people during the peak hours? Ideally, the queue is waiting. Ideally, there is no order in the waiting queue. Some are just fist and power, and there is no way, li Gang is the father of other people, and the target person is okay, not to mention waiting in line to buy tickets. Wang fa is what people say. Of course, let's look at the specific program.

Java code

<Span style = "font-size: small;"> package threadConcurrent. test;

 

Import java. util. Random;

Import java. util. concurrent. Semaphore;

 

/**

* Use Semaphore to limit the number of threads that can be executed and put idle resources into the queue for waiting

*

* @ Author liuyan

*/

Public class SemaphoreDemo {

 

Public static void main (String [] args ){

Runnable limitedCall = new Runnable (){

 

// Number of randomly generated data

Final Random rand = new Random ();

 

// Only three resources are allowed to be active. If the second parameter is set to true, the first-in-first-out mode is implemented according to the standard "queue" structure.

Final Semaphore available = new Semaphore (5, true );

Int count = 0;

 

Public void run (){

Int time = rand. nextInt (10 );

Int num = count ++;

 

Try {

 

// Request resources

Available. acquire ();

 

Int needTime = time * 2000;

 

System. out. println ("passenger" + num + "required for ticket purchase [" + needTime

+ "Seconds]... #");

 

Thread. sleep (needTime );

 

System. out. println ("passenger" + num + "purchased #! ");

 

// Release after running

Available. release ();

} Catch (InterruptedException intEx ){

IntEx. printStackTrace ();

}

}

};

 

For (int I = 0; I <25; I ++)

New Thread (limitedCall). start ();

}

} </Span>

The comment has been clearly written. When Semaphore is built, the first parameter represents the maximum number of thread executions, the second parameter is to put the unexecuted threads into the queue in the form of a queue. After a thread is executed, it will follow the principle of first-in-first-out to wake up and execute the thread. Even if the main node starts 25 threads, the other threads must be executed before they can be executed. To make the thread run according to the rules, you must first apply for resources from the resource pool, available. acquire (); is to request the resource pool to give a resource. If there are currently idle resources in the resource pool, the thread can run normally. If there is no such resource pool, there is no way to queue. After the thread is running, remember to return the resource available. release (); if the second parameter is not specified when Semaphore is constructed, or the second parameter is false, it is estimated that you have the honor to see the phenomenon of Li Gang's son I mentioned earlier! I will not go into details here.

4. ScheduledFuture

Speaking of Quartz, we all know that Quartz is an open-source tool responsible for task scheduling. It can be used to easily execute related business functions at a certain frequency during a certain period of time. If you simply execute some tasks based on certain time frequencies, but you don't need to kill the chicks, you can use ScheduledFuture to easily solve the problem of such frequencies and start another thread, execute Code at a certain frequency. Let's take another example. In the age of war, Zhao Yun took a small soldier to patrol the city. Zhao Yun was a general and inspected the soldiers every five seconds to see if they were lazy and the soldiers were tired, the city guard is inspected once every second and cannot go to bed. The following procedure

Java code

<Span style = "font-size: small;"> package threadConcurrent. test;

 

Import static java. util. concurrent. TimeUnit. SECONDS;

 

Import java. util. Date;

Import java. util. concurrent. Executors;

Import java. util. concurrent. ScheduledExecutorService;

Import java. util. concurrent. ScheduledFuture;

 

/**

* Time Frequency Scheduling

* @ Author liuyan

*/

Public class ScheduledFutureDemo {

 

@ SuppressWarnings ("unchecked ")

Public static void main (String [] args ){

 

// Two threads are created in the thread pool.

Final ScheduledExecutorService schedors = Executors

. NewScheduledThreadPool (2 );

 

// General

Final Runnable general = new Runnable (){

Int count = 0;

 

Public void run (){

System. out. println (Thread. currentThread (). getName () + ":"

+ New Date () + "Zhao yuninspection" + (++ count ));

}

};

// Soldiers

Final Runnable soldier = new Runnable (){

Int count = 0;

 

Public void run (){

System. out. println (Thread. currentThread (). getName () + ":"

+ New Date () + "Soldiers visited" + (+ + count ));

}

};

 

// Run every two seconds after 1 second

Final ScheduledFuture beeperHandle1 = scheduler. scheduleAtFixedRate (

Soldier, 1, 1, SECONDS );

 

// Run every 2 seconds after 5 seconds

Final ScheduledFuture beeperHandle2 = scheduler. scheduleWithFixedDelay (

General, 5, 5, SECONDS );

 

// Close the task 30 seconds later and close Scheduler

Schedable. schedule (new Runnable (){

Public void run (){

BeeperHandle1.cancel (true );

BeeperHandle2.cancel (true );

Scheddown. shutdown ();

}

}, 60, SECONDS );

}

 

}

</Span>

 

The comments of the program are clear and will not be repeated here.

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.