Multithreading 002 and Multithreading

Source: Internet
Author: User

Multithreading 002 and Multithreading

Zookeeper java. util. concurrent. CountDownLatch is a synchronization helper class provided by JDK 1.5. It allows one or more threads to wait until a group of operations in other threads are completed.

When CountDownLatch is initialized, the specifiedCount. The await method is blocked until the current count reaches zero by calling the countDown method. Then, all the waiting threads will be released, and the operations after await will be executed immediately. This operation only appears once because the Count cannot be reset. To reset the count, consider using java. util. concurrent. javasicbarrier.

Zookeeper CountDownLatch is a common synchronization tool that has many uses. CountDownLatch initialized with 1 can be used as a simple ON/OFF lock or entry: Before a thread calls countDown to open the entry, all the threads that call await will wait until the entry is opened. CountDownLatch initialized with N (N> = 1) enables a thread to wait until N threads complete a certain operation, or wait until a certain operation is completed N times.

A useful feature of CountDownLatch is that it does not block the thread that calls the countDown method until the count reaches 0, it only stops all the threads that call await from executing the operations after await.

CountDownLatch has two typical usage methods:

Two counters

Sample Code:

Public class CountDownLatchTest {public static void main (String [] args) throws limit {CountDownLatch startSignal = new CountDownLatch (1); // The first condition CountDownLatch doneSignal = new CountDownLatch (N ); for (int I = 0; I <N; ++ I) {new Thread (new Worker (startSignal, doneSignal )). start ();} doSomethingElse (); startSignal. countDown (); // start doSomethingElse (); doneSignal. await (); // wait until all operations are completed} class Worker implements Runnable {private final implements startSignal; private final CountDownLatch doneSignal; Worker (CountDownLatch startSignal, CountDownLatch doneSignal. startSignal = startSignal; this. doneSignal = doneSignal;} @ Override public void run () {try {startSignal. await (); // wait until the first condition ends doWork (); doneSignal. countDown ();} catch (InterruptedException ex) {}} void doWork (){...}}

In the sample code, startSignal isPrerequisitesIn this example, the initial count is 1, which is a simple switch. For example, in a-meter track and field competition, athletes are waiting before the starting gun rings. After the starting gun rings, the athletes start the competition and wait until the last athlete reaches the end and the competition ends.

Simple code implementation:

Package howe. demo. thread. countdown; import java. util. random; import java. util. concurrent. countDownLatch; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. timeUnit;/*** @ author liuxinghao * @ version 1.0 Created on September 15, 2014 */public class CountDownLatchTest {public static void main (String [] args) throws InterruptedException {final CountDo WnLatch begin = new CountDownLatch (1); final CountDownLatch end = new CountDownLatch (3); final ExecutorService exec = Executors. newFixedThreadPool (3); for (int index = 0; index <3; index ++) {exec. submit (new Runner (index + 1, begin, end);} System. out. println ("everybody... "); System. out. println (" preparation... "); System. out. println (" success... "); Begin. countDown (); end. await (); System. out. println (" the competition is over and the awards are ready. "); Exec. shutdown () ;}} class Runner implements Runnable {private int no; private CountDownLatch begin; private CountDownLatch end; public Runner (int no, CountDownLatch begin, CountDownLatch end) {this. no = no; this. begin = begin; this. end = end; System. out. println ("No. "+ no +" reaches the starting line. ") ;}@ Override public void run () {try {begin. await (); // wait for the starting gun to ring the System. out. println ("No. "+ no +" galloping forward... "); TimeUnit. SECONDS. sleep (new Random (). nextInt (10); // running process...} Catch (InterruptedException e) {} System. out. println ("No." + no + "to the end. "); End. countDown ();}}

Extended, begin to define a series of execution chains. The first is to execute directly without any precondition, the second is to determine the first condition, and so on. I am a lazy, and I will not repeat it too much. A friend of mine wrote well: Using CountDownLatch to synchronize threads

One counter

When the primary thread crashes a counter, it feels that the situation is relatively simple, that is, the main thread waits for the sub-thread to end, and then continues to execute. Here, the main thread and sub-thread are relatively speaking. Maybe the main thread itself is the sub-thread of another thread.

Sample Code:

Public class CountDownLatchTest6 {public static void main (String [] args) throws InterruptedException {CountDownLatch doneSignal = new CountDownLatch (3); ExecutorService e = Executors. newCachedThreadPool (); for (int I = 0; I <3; ++ I) {e.exe cute (new Worker (doneSignal, I);} doSomethingElse (); doneSignal. await (); // wait until the sub-thread ends doSomethingElse (); e. shutdown () ;}} class Worker implements Runnable {private final CountDownLatch doneSignal; private final int id; Worker (CountDownLatch doneSignal, int id) {this. doneSignal = doneSignal; this. id = id ;}@ Override public void run () {doWork (); doneSignal. countDown ();} void doWork (){...}}

The doSomethingElse method in the zookeeper sample code can be some business logic code, which varies according to specific functions.

For this method, refer to the second solution in the previous example about the boss and the worker. multithreading 001-the main thread waits for the sub-thread to end.


JAVA simple socket program

CS001 is the client that starts sending information ~ This is the question I want to participate in the competition prediction, and then I will change it slightly to meet your requirements ~ Server: import java. awt .*;
Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import java. awt. event. ItemEvent;
Import java. awt. event. ItemListener;
Import java. awt. event. WindowAdapter;
Import java. awt. event. javaswevent;
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java.net. *; import javax. swing. JOptionPane; public class GUI and multithreading extends Frame implements ActionListener, ItemListener
{
Panel p1, p2, p3;
Checkbox c1, c2;
CheckboxGroup group;
TextArea text1 = null, text2 = null;
TextField tf = null;
Button send, exit;
CS001Thread th1 = null;
CS002Thread Th1 = null;
Int flag = 0;
Public GUI and multithreading (String title)
{
Super (title );
P1 = new Panel ();
Group = new CheckboxGroup ();
C1 = new Checkbox ("CS001", group, false );
C2 = new Checkbox ("CS002", group, false );
P1.add (c1 );
P1.add (c2 );
P1.add (new Label ("sales Info", Label. RIGHT ));
P2 = new Panel ();
Text1 = new TextArea (30, 25 );
Text1.setEditable (false );
Text2 = new TextArea (30, 25 );
Text2.setEditable (false );
P2.add (text1 );
P2.add (text2 );

P3 = new Panel ();
Tf = new TextField (20 );
Send = new Button ("send ");
Exit = new Button ("exit ");
P3.add (new Label ("input information "));
P3.add (tf );
P3.add (send );
P3.add (exit );

Add (p1, "North ");
Add (p2 );
Add (p3, "South ");

SetSize (480,300 );
SetVisible (true );

Send. addA ...... full text>

AfxBeginThread function problems

UINT threadMy1 (LPVOID lpParameter); // thread 1

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.