Java Threading Summary (ii)

Source: Internet
Author: User

The data for custom threads can be shared or not shared, depending on how it is implemented.

1. Do not share the data multithreading implementation method:

 Public classMyThreadextendsthread{Private intCount = 4;  PublicMyThread (String threadname) { This. SetName (ThreadName); } @Override Public voidrun () { while(Count > 0) {Count= Count-1; System.out.println ("By" + Thread.CurrentThread (). GetName () + "calculation, Count =" +count); Try{Thread.Sleep (1000); }Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {MyThread Threada=NewMyThread ("A"); MyThread threadb=NewMyThread ("B"); MyThread THREADC=NewMyThread ("C");        Threada.start ();        Threadb.start ();    Threadc.start (); }}

The results of the implementation are as follows:

From the results, each thread is printed at 3, then 2, then 1, 0. It can be concluded that each thread has a copy of the variable count, which is not disturbed by other threads.

2. Multi-threaded implementation of shared data

 Public classMyThreadextendsthread{Private intCount = 4; @Override Public voidrun () { while(Count > 0) {Count= Count-1; System.out.println ("By" + Thread.CurrentThread (). GetName () + "calculation, Count =" +count); Try{Thread.Sleep (1000); }Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {MyThread MyThread=NewMyThread (); Thread a=NewThread (MyThread, "A"); Thread b=NewThread (MyThread, "B"); Thread C=NewThread (MyThread, "C"); Thread D=NewThread (MyThread, "D");        A.start ();        B.start ();        C.start ();    D.start (); }}

The results of the implementation are as follows:

As the result shows, a,b,c,d four threads share a variable count

Java Threading Summary (ii)

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.