This article mainly summarizes the relevant knowledge of thread sharing data, which mainly includes two aspects: one is how to share data within a certain thread to ensure that the data of each thread does not intersect; the other is how to share data between multiple threads to ensure the consistency of data.
If you implement it yourself, you define a map, the thread is the key and the data is the value. Each item in the table is the data prepared for each thread, so that the data is consistent in one thread.
example
package com.iot.thread;import java.util.HashMap;import java.util.Map;import java.util.Random;/** * Created by brian on 2016/2/4. */public class ThreadScopeShareData {//Prepare a hash table to prepare data for each thread private static Map<Thread,Integer> threadData = new HashMap<>();public static void main(String[] args) {for (int i=0;i<2;i++){new Thread( new Runnable() {@Override public void run() {int data = new Random().nextint();threadData.put(Thread.currentThread(),data);System.out.println(Thread.currentThread()+" put data: "+data);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from "+Thread.currentThread()+" get data "+data);}}static class B{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("B from "+Thread.currentThread()+" get data "+data);}}}The above code occasionally reports exceptions:
Exception in thread "Thread-0" java.lang.NullPointerException
at com.iot.thread.ThreadScopeShareData$A.get(ThreadScopeShareData.java:29)
at com.iot.thread.ThreadScopeShareData$1.run(ThreadScopeShareData.java:21)
at java.lang.Thread.run(Thread.java:745)
I don't know the specific reason yet
API:
java.lang:Class ThreadLocal<T>
Use ThreadLocal object instead of the above map
Define an object to encapsulate multiple variables and then store the entire object in ThreadLocal
When multivariate, it is best to place the ThreadLocal class inside the data class. The data class adopts a singleton mode, so that it will be more convenient to create new objects and obtain objects, and at the same time it is more encapsulation.
package com.iot.thread;import java.util.Random;/** * Created by brian on 2016/2/4. */public class ThreadLocalTest {private static ThreadLocal<Integer> threadInger = new ThreadLocal<>();public static void main(String[] args) {for (int i=0;i<2;i++){new Thread(new Runnable() {@Override public void run() {int data = new Random().nextint(100);threadInger.set(data);System.out.println(Thread.currentThread()+" put data: "+data);MyThreadScopeData.getThreadInstance().setName(Thread.currentThread().toString());MyThreadScopeData.getThreadInstance().setAge(data%10);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadInger.get();System.out.println("A from "+Thread.currentThread()+" get data "+data);MyThreadScopeData myThreadScopeData = MyThreadScopeData.getThreadInstance();System.out.println("A from "+myThreadScopeData);}}static class B{public void get(){int data = threadInger.get();System.out.println("B from "+Thread.currentThread()+" get data "+data);MyThreadScopeData myThreadScopeData = MyThreadScopeData.getThreadInstance();System.out.println("B from "+myThreadScopeData);}}}/** * Data class encapsulating multivariables* Singleton mode, built-in ThreadLocal type variable*/class MyThreadScopeData{private MyThreadScopeData(){}private static ThreadLocal<MyThreadScopeData> data = new ThreadLocal<>();public static MyThreadScopeData getThreadInstance(){MyThreadScopeData instance = data.get();if(instance == null){instance = new MyThreadScopeData();data.set(instance);}return instance;}private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Override public String toString() {String reVal = super.toString()+"-{name,age}"+":{"+getName()+","+getAge()+"}";return reVal;}}Several ways
An example of the last method:
Design 5 threads, three threads increase by 1 each time for j, and the other two threads decrease by 1 each time for j
package com.iot.thread;/** * Created by brian on 2016/2/4. */public class MutiThreadShareData {private static MutiShareData mutiShareData = new MutiShareData();public static void main(String[] args) {for (int i=0;i<3;i++){new Thread( new Runnable() {@Override public void run() {System.out.println(Thread.currentThread()+":{j from "+ mutiShareData.getJ()+" + to: "+mutiShareData.increment()+"}");}}).start();} for (int i=0;i<2;i++){new Thread( new Runnable() {@Override public void run() {System.out.println(Thread.currentThread()+":{j from "+mutiShareData.getJ()+" - to: "+mutiShareData.decrement()+"}");}}).start();}}}/** * Encapsulate shared data in another object (the method of manipulating data is also completed in that object) */class MutiShareData{private int j = 0;public synchronized int increment(){return ++j;}public synchronized int decrement(){return --j;}public synchronized int getJ() {return j;}public synchronized void setJ(int j) {this.j = j;}}The above is all the detailed explanation of Java programming multi-threaded shared data code, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!