Record a trip back to the tech. Thread-related pen question, three thread addition and one thread subtraction, two threads of the extension are executed alternately

Source: Internet
Author: User
Tags modifier object object

Today, I went back to the technology test. Unfortunately, the head has a mind but not yet to the level of proficiency in handwriting code, basic skills are not in place.

First: Thread of the topic: three threads + 11 threads-1 operations.

See there are four threads on the web, two addition calculations, and two subtraction operations. The basic ideas are the same, pay attention to the synchronous processing.

The following code implementation is posted:

public class Addtest {    private static int i;    private static Object object = new Object ();    public static void Main (string[] args) {                    new Thread ((), {            synchronized (object) {                i++;            }        }). Start ();        New Thread ((), {            synchronized (object) {                i++;            }        }). Start ();        New Thread ((), {            synchronized (object) {                i++;            }        }). Start ();        New Thread ((), {            synchronized (object) {                i--;            }        }). Start ();
Here sleep and so on all threads run finished see the final value, 2 try { thread.sleep (+); } catch (Interruptedexception e) { E.printstacktrace (); } System.out.println (i); }}



This brings out the other issues of thought

The 1th type:
synchronized void add modifier common method is equivalent to
Synchronized (This)
  public int i = 0;    public void Add (String threadname) {        synchronized (this) {            i++;            System.out.println (ThreadName + "addition operation:" + i);        }    } The above code equals the following code: public   synchronized void Add (String threadname) {              i++;            System.out.println (ThreadName + "addition operation:" + i);          }

  

The 2nd type:
Synchronized static void the Add modifier is equivalent to
  synchronized (*.class) 

Description: The above two I analysis for the synchornized modification of the normal method and this corresponds to the same instance object. The modified static method and class are the only class objects that correspond to the same classes. This is my understanding, there are mistakes, please correct me. Thank you here

second way:
One thread adds an operation, one thread does the subtraction operation, and multiple threads alternately run (enshin)

1th method: Implement with synchronized
public class Count {    private int num = 0;    Private Boolean flag = false; Identity    //addition public    synchronized void Add () {        while (flag) {            try {                wait ();            } catch ( Interruptedexception e) {                e.printstacktrace ();            }        }        this.num++; Add        System.out.println (Thread.CurrentThread (). GetName () + "..." + this.num);        This.flag = true; Set the identity to True        Notifyall ();//wake all threads that are frozen in thread pool, will wake all up    }    //Subtract public    synchronized void Sub () {        while (!flag) {            try {                wait ();            } catch (Interruptedexception e) {                e.printstacktrace ()}        }        this.num--;//Minus        System.out.println (Thread.CurrentThread (). GetName () + "..." + this.num);        This.flag = false; Set the identity to True        Notifyall ();//wake all threads that are frozen in the thread pool and wake them all up    }}

2nd: Use lock lock to implement

public class Countlock {private int num = 0; Private Boolean flag = false; Identify lock lock = new Reentrantlock (); Lock Condition add = Lock.newcondition ();            Addition Lock Condition sub = Lock.newcondition ();//subtraction lock public void Add () {lock.lock ();//Lock try {            while (flag) {//Cycle judgment add.await ();            } this.num++;            System.out.println (Thread.CurrentThread (). GetName () + "..." + this.num); This.flag = true; Set the identity sub.signal ();        Wake-up specified thread} catch (Interruptedexception e) {e.printstacktrace ();        } finally {Lock.unlock (); }} public void sub () {Lock.lock ();//Lock try {while (!flag) {//Loop judgment Sub.aw            AIT ();            } this.num--;            System.out.println (Thread.CurrentThread (). GetName () + "..." + this.num); This.flag = false; Set the identity add.signal ();      Wake the specified thread  } catch (Interruptedexception e) {e.printstacktrace ();        } finally {Lock.unlock (); }    }}

  

Call the Main method:
    public static void Main (string[] args) {        //count c=new Count ();        Countlock c=new Countlock ();        Thread T1=new Thread (new Runnable () {            @Override public            void Run () {                while (true) {                    c.add ()                }            }        });        Thread T2=new Thread (new Runnable () {            @Override public            void Run () {                while (true) {                    c.sub ()                }            }        });        T1.start ();        T2.start ();   There is a sense that fewer threads can start two T3 or T4 to verify authenticity    }

  

This Rienschen Knowledge Point reference Blog:
Java synchronized modifies common methods, modifies static methods, modifies code blocks, modifies thread run method comparisons


Record a trip back to the tech. Thread-related pen question, three thread addition and one thread subtraction, two threads of the extension are executed alternately

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.