There are many ways to access shared objects and data from multiple threads, but they can be divided into two main categories: 1. Multithreaded execution code is the same. 2. Multithreaded execution code is different
For the same scenario where multithreaded execution code is:
1) using the same Runnable object, put the same object in the new thread
public static void Main (string[] args) {Runnable r = new Runnable () {int num = +; @Overridepublic synchronized void Run () {System.out.println (++num + "==add");}; thread T1 = new Thread (r); Thread t2 = new Thread (r); thread t3 = new Thread (r); T1.start (); T2.start (); T3.start ();}
For situations where multithreaded code is different:
1) The object or data that needs to be shared is placed in another object, which provides methods for its operation to be invoked by different threads.
Class Number {int num = 100;public int Add () {return ++num;} public int del () {return--num;}}
Using the same number object in a Runnable object
public static void Main (string[] args) {final number num = new number (); Runnable radd = new Runnable () {@Overridepublic synchronized void run () {System.out.println (Num.add () + "==add");}}; Runnable Rdel = new Runnable () {@Overridepublic synchronized void run () {System.out.println (Num.del () + "==del");}}; thread T1 = new Thread (RADD); Thread t2 = new Thread (Rdel); thread t3 = new Thread (RADD); T1.start (); T2.start (); T3.start ();}
2) write runnable in the form of an inner class, and then write the objects and data that need to be shared into the member variables of the outer class.
Class Number{int num = 100; Runnable R_add = new Runnable () {@Overridepublic synchronized void run () {System.out.println (++num+ "==add");}}; Runnable R_del = new Runnable () {@Overridepublic synchronized void run () {System.out.println (--num+ "==del");}};}
It is then implemented by invoking the inner class object in the Number object.
public static void Main (string[] args) {Number n = new number (); thread T1 = new Thread (N.R_ADD); Thread t2 = new Thread (N.r_del); T1.start (); T2.start ();}
------------------------------------------------------------------------------
Another way to be simple and rude is to modify the objects and data you want to share with static.
Multiple threads accessing shared objects and data