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 ();}}