Three thread ABC, alternating print abc_ concurrent programming

Source: Internet
Author: User
Tags semaphore static class
Synchronized

The problem is the synchronous wake-up operation between three threads, the main purpose is to Threada->threadb->threadc→threada ... Loops through three threads. In order to control the order in which the threads are executed, you must determine the order in which to wake and wait, so each thread must hold two object locks in order to continue execution. An object lock is a prev, which is the object lock held by the previous thread. Another is the object lock itself.

The main idea is that in order to control the order of execution, we must first hold the Prev lock, that is, the previous thread to release its own object lock, then to apply for its own object lock, both when printing letters, and then first call Self.notifyall () release its own object lock, wake the next waiting thread, Then call Prev.wait () to release the Prev object lock, terminate the current thread, and wake up again after the loop is over. The main process of running a program is that a thread runs first, holds the C,a object lock, releases the A,c lock, and wakes up B. Thread B Wait for a lock, then apply for B lock, print B, then release b,a lock, Wake C, thread C wait for B lock, then apply for C lock, print C, then release C,b lock, Wake a ...

To avoid the uncertainty of the JVM starting Threada, THREADB, THREADC three thread order. You need to have a,b,c three threads start in a determined order, with a section of sleep in between to ensure that the previous thread is started.

public class ABC {public static class Threadprinter implements Runnable {private String name;
        Private Object prev;
 
        Private Object self;
            Private Threadprinter (String name, Object prev, object self) {this.name = name;
            This.prev = prev;
        This.self = self;
            @Override public void Run () {int count = 10;
                    while (Count > 0) {//multithreaded concurrency, cannot use if, must use cyclic test wait condition, avoid false wake-up synchronized (prev) {//Get prev Lock First
                        Synchronized (self) {//RE acquires self lock System.out.print (name);
 
                        count--; Self.notifyall ();//release self first, wake other threads to compete self lock} try {Prev.wa     It (); Then release prev, Hibernate waiting to wake/** * Note that after the Notify () call, not immediately release the object lock, but in the corresponding synchronized () {} statement block execution end, lock automatically released, * JVMRandomly selects a thread in a wait () object lock, gives its object lock, wakes the thread, and continues execution.
                    */} catch (Interruptedexception e) {e.printstacktrace ();
        "}}}} public static void Main (string[] args) throws Exception {
        Object A = new object ();
        Object B = new Object ();
        Object c = new Object ();
        Threadprinter pa = new Threadprinter ("A", C, a);
        Threadprinter PB = new Threadprinter ("B", A, b);
 
 
        Threadprinter pc = new Threadprinter ("C", B, c);
        New Thread (PA). Start ();
        Thread.Sleep (10);
        New Thread (Pb). Start ();
        Thread.Sleep (10);
        New Thread (PC). Start ();
    Thread.Sleep (10); }
}
Lock
public class Abc_lock {private static lock lock = new Reentrantlock ()//Lock lock in JDK5 to guarantee thread access mutex private static I
 
    NT state = 0;  Static Class Threada extends Thread {@Override public void run () {for (int i = 0; i < 10;
                    ) {try {lock.lock ();
                        while (state% = 3 = 0) {//multithreading concurrency, cannot use if, must use cyclic test wait condition, avoid false wake-up System.out.print ("A");
                        state++;
                    i++;
            finally {lock.unlock ();//Lock () and unlock () operation combined with Try/catch use}
            }} static Class Threadb extends Thread {@Override public void run () { for (int i = 0; i < 10;)
                    {try {lock.lock ();
            while (state% = 3 = 1) {//multithreading concurrency, cannot use if, must use cyclic test wait condition, avoid false wake-up System.out.print ("B");            state++;
                    i++;
            finally {lock.unlock ();//Lock () and unlock () operation combined with Try/catch use}
            }} static Class Threadc extends Thread {@Override public void run () { for (int i = 0; i < 10;)
                    {try {lock.lock ();
                        while (state% 3 = = 2) {//multithreaded concurrency, cannot use if, must use cyclic test wait condition, avoid false wake-up System.out.print ("C");
                        state++;
                    i++;
            finally {lock.unlock ();//Lock () and unlock () operation combined with Try/catch use}
        }} public static void Main (string[] args) {new Threada (). Start ();
        New Threadb (). Start ();
    New THREADC (). Start (); }
}
Condition
public class Abc_condition {private static lock lock = new Reentrantlock ();
    private static Condition A = Lock.newcondition ();
    private static Condition B = Lock.newcondition ();
 
    private static Condition C = Lock.newcondition ();
 
    private static int count = 0; Static Class Threada extends Thread {@Override public void run () {try {lock
                . Lock (); for (int i = 0, I < i++) {while (count% 3!= 0) a.await ()//A release lock
                    Lock System.out.print ("A");
                    count++; B.signal ();
            A wake up B thread} catch (Interruptedexception e) {e.printstacktrace ();
            finally {Lock.unlock (); }} static Class Threadb extends Thread {@Override public void run () {TR
   y {lock.lock ();             for (int i = 0, I < i++) {while (count% 3!= 1) b.await (
                    );/b Release lock lock System.out.print ("B");
                    count++; C.signal ()//b wakes up C thread} catch (Interruptedexception e) {E.printstacktrace
            ();
            finally {Lock.unlock (); }} static Class Threadc extends Thread {@Override public void run () {TR
                y {lock.lock (); 
                    for (int i = 0; i < i++) {while (count% 3!= 2) c.await ();//C Release lock lock
                    System.out.println ("C");
                    count++; A.signal ()//C finish wake a thread} catch (Interruptedexception e) {E.printstacktrace
            ();
          finally {Lock.unlock ();  }} public static void Main (string[] args) throws interruptedexception {new Threada (). Start
        ();
        New Threadb (). Start ();
        THREADC THREADC = new THREADC ();
        Threadc.start ();
    Threadc.join ()//main thread calls Threadc.join (), and waits until THREADC execution completes, then executes main thread System.out.println (count);
 }
}
Semaphore
public class Abc_semaphore {//The semaphore starting with a, the initial semaphore amount is 1 private static semaphore A = new semaphore (1);
    b, C signal volume, a completion of the start, the initial signal number is 0 private static semaphore B = new semaphore (0);
 
    private static semaphore C = new semaphore (0); Static Class Threada extends Thread {@Override public void run () {try { (int i = 0; i < i++)
                    {A.acquire ();/A Get Signal execution System.out.print ("a"); B.release ()//b releases the signal, B semaphore is 1, can perform} catch (Interruptedexception e) {e.prints
            Tacktrace (); }} static Class Threadb extends Thread {@Override public void run () {TR
                    y {for (int i = 0; i < i++) {b.acquire ();
                    System.out.print ("B");
                C.release ();
 } catch (Interruptedexception e) {               E.printstacktrace (); }} static Class Threadc extends Thread {@Override public void run () {TR
                    y {for (int i = 0; i < i++) {c.acquire ();
                    System.out.println ("C");
                A.release ();
            } catch (Interruptedexception e) {e.printstacktrace (); }} public static void Main (string[] args) throws interruptedexception {new Threada (). Start ()
        ;
        New Threadb (). Start ();
    New THREADC (). Start (); }
}

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.