Java programming multi-threaded shared data code details, java programming multi-threaded details

Source: Internet
Author: User

Java programming multi-threaded shared data code details, java programming multi-threaded details

This article mainly summarizes the knowledge about thread-based data sharing, including two aspects: first, how to share data in a thread to ensure that data in each thread is not crossed; first, how to share data among multiple threads to ensure data consistency.

Share data within the thread range

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 in one thread is consistent.

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 and prepare private static Map <Thread, Integer> threadData = new HashMap <> () for each Thread (); 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 (). 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 an exception:

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)

The specific reason is unknown.

ThreadLocal class

API:

Java. lang: Class ThreadLocal <T>

  • Single Variable

Use the ThreadLocal type object instead of the above Map.

  • Multi-Variable

Define an object to encapsulate multiple variables, and then store the entire object in ThreadLocal

When there are multiple variables, it is best to place the ThreadLocal class inside the data class. The data class adopts the single-instance mode, which makes it easier to create and obtain objects, and is more encapsulated.

Sample Code:
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 (). 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 * Singleton mode encapsulated by multiple variables, 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 ;}}
Multi-threaded access to shared data

Several Methods

  • The same Runnable object is used when the thread executes the same code. The Runnable object contains shared data.
  • Different code is executed by the thread. The shared data is encapsulated in another object (the method for operating data is also completed in this object), and this object is passed to each Runnable object one by one. [Essence: the object of shared data is passed into the Runnable object as a parameter]
  • Different code is executed by threads. the Runnable object is used as the internal class of a class, and the shared data is used as the member variable of this external class (the method for operating data is placed in the external class ). [Essence: Different Internal classes share external class Data]
  • In combination with the above two methods, shared data is encapsulated in another object (the data operation method is also completed in this object), the object as a member variable of this external class, use Runnable object as internal class

Example of the last method:

Design five threads. Three of them increase by 1 for j each time, and the other two threads decrease by 1 for j each time.

Package com. iot. thread;/*** Created by brian on 2016/2/4. */public class mutithreadincludata {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 the shared data in another object (the data operation method is also completed in this 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 ;}}
Summary

The above is all the details about the shared data code of Java programming multithreading, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

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.