(1) When accessing the common code : You can use the same Runnable object , This Runnable object has this shared data , such as the ticketing system can do so. Or the shared data is encapsulated in an object and then locked to the object, which can also be used for 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 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 each thread accesses a different code : this time to use a different runnable object,
The Runnable object is used as an inner class in a class, the shared data as a member variable of the external class, and each thread's access to the shared data is also passed to the external class's method, which is mutually exclusive and communicates with the shared data. The Runnable object invokes the operation of the external class for this shared data method.
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 (); } } /** * implementing shared variables for threads through internal classes * */ class mythread { int index = 0; private class InnerThread extends Thread { &nbSp; public synchronized void run () { while (True) { system.out.println (Thread.currentThread (). GetName () + "is running and index is " + index++); } } } public thread getthread () { return new innerthread (); } }
Reference article:
http://my.oschina.net/u/248570/blog/53226
This article is from the "Nothing-skywalker" blog, please be sure to keep this source http://tianxingzhe.blog.51cto.com/3390077/1693465
Shared variables for the Java multithreaded communication