Shared variables for java multi-thread Communication

Source: Internet
Author: User

Shared variables for java multi-thread Communication
(1) when accessing the Common Code: You can use the same Runnable object, which contains the shared data, such as the ticket selling system. Or the shared data is encapsulated in an object, and the object is locked. This can also achieve secure data access.

Public class Interfacaesharethread {public static void main (String [] args) {Mythread1 mythread = new Mythread1 (); new Thread (mythread ). start (); new Thread (mythread ). start (); new Thread (mythread ). start (); new Thread (mythread ). start () ;}}/* implement the Runnable interface */class Mythread1 implements Runnable {int index = 0; public synchronized void run () {while (true) System. out. println (Thread. currentThread (). getName () + "is running and the index is" + index ++ );}}

 

(2) When different threads access different codes: At this time, different Runnable objects should be used to take the Runnable object as the internal class in a class, shared data is a member variable of this external class. Each thread's access to shared data is also handed over to the external class method, so that the shared data is mutually exclusive and communicated. The Runnable object calls the external class operation to share data.
Public class Innersharethread {public static void main (String [] args) {Mythread mythread = new Mythread (); mythread. getThread (). start (); mythread. getThread (). start (); mythread. getThread (). start (); mythread. getThread (). start () ;}}/*** share variable of thread through internal classes **/class Mythread {int index = 0; private class InnerThread extends Thread {public synchronized void run () {while (true) {System. out. println (Thread. currentThread (). getName () + "is running and index is" + index ++) ;}} public Thread getThread () {return new InnerThread ();}}

 

 

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.