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