Java two useful helper classes for multithreading (Countdownlatch and Atomicboolean)

Source: Internet
Author: User

Atomicboolean can have one thread wait for another thread to complete the task before executing it:

A Boolean value is updated atomically. The Java.util.concurrent.atomic package specification for description of the properties of atomic variables. An atomicboolean was used in applications such as atomically updated flags, and cannot to be used as a replacement for a Boole An.

public static void Main (string[] args) {
		thread t2 = new Thread (new Barworker ("BB"));
		thread T1 = new Thread (new Barworker ("AA"));
		T2.run ();
		T1.run ();
	}

	
	private static class Barworker implements Runnable {

		private static atomicboolean exists = new Atomicboolean (false); 
  private String name;

		Public Barworker (String name) {
			this.name = name;
		}

		public void Run () {
			if (Exists.compareandset (False, True)) {  //when the first thread is set to True, the other thread is not coming
				
				in SYSTEM.OUT.PRINTLN (name + "enter" + "currentvalue=" +exists.get ());
				try {
					System.out.println (name + "working");
					Thread.Sleep ();
				} catch (Interruptedexception e) {
					//Do nothing
				}
				System.out.println (name + "Leave");
				Exists.set (false);
			else {
				System.out.println (name + "Give Up");}}

	

Results of Printing:

BB entercurrentvalue=true
bb working
BB leave
aa entercurrentvalue=true
aa working
AA leave

Countdownlatch

A synchronization helper class that allows one or more threads to wait all the time before completing a set of operations that are being performed in another thread.

If the final countdownlatch end = new Countdownlatch (10) is set; End.countdown (); Can reduce count

If you write end.await in a certain place (); If the count is not 0, all threads will wait and the count will not be reset


private static  Countdownlatch Mlatch = new Countdownlatch (5);
	
	public static void Main (string[] args) throws Interruptedexception {


        final executorservice exec = Executors.newfixedt Hreadpool (ten);  

        for (int index = 0; index < 5; index++) {
            final int NO = index + 1;  
            Runnable run = new Runnable () {public
                void run () {  
                    try {  
                    	System.out.println (NO + "working");
        				Thread.Sleep ();
                    } catch (Interruptedexception e) {  
                    } finally {  
                    	mlatch.countdown ();
                    }}}  
            ;  
            Exec.submit (run);

        }  
        Mlatch.await ();  
        System.out.println ("Finish");  
        Exec.shutdown ();  
    }

Results:

1 Working
3 working
2 working
4 working
5 working
finish






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.