이 기사는 주로 두 가지 측면을 포함하는 스레드 공유 데이터에 대한 관련 지식을 주로 요약합니다. 하나는 각 스레드의 데이터가 교차하지 않도록 특정 스레드 내에서 데이터를 공유하는 방법입니다. 다른 하나는 데이터의 일관성을 보장하기 위해 여러 스레드간에 데이터를 공유하는 방법입니다.
직접 구현하면 맵을 정의하고 스레드가 키이고 데이터는 값입니다. 테이블의 각 항목은 각 스레드에 대해 준비된 데이터이므로 데이터가 하나의 스레드에서 일관되게됩니다.
예
package com.iot.thread; import java.util.hashmap; import java.util.map; import java.util.random;/*** Brian이 2016/2/4에 작성했습니다. */public class stroodscopesharedata {// 각 스레드에 대한 데이터를 준비하기 위해 해시 테이블 준비 개인 정적 맵 <스레드, 정수> threaddata = new Hashmap <> (); public static void main (string [] args) {for (int i = 0; i <2; i ++) {new run (new Runnable Public Run () {int void run () {int void run () random (). nextInt (); threadData.put (Thread.currentThread (), data); system.out.println (strook.currentThread ()+"put data :"+data); new a (). get (); new B (). start ();}} static class a {int data = {int data = {int data = {int data =. ThreadData.get (Thread.CurrentThread ()); System.out.println ( "a from"+orth thread.currentThread ()+"get data"+data);}} 정적 클래스 b {public void get () {int data = threaddata.get (thread.currentthread ()); system.out.println ( "b from"+"+"+"+"+" "+data);}}}위의 코드는 때때로 예외를보고합니다.
스레드 "스레드 -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)
나는 아직 구체적인 이유를 모른다
API :
java.lang : 클래스 스레드 로컬 <t>
위의 맵 대신 ThreadLocal 객체를 사용하십시오
객체를 정의하여 여러 변수를 캡슐화 한 다음 전체 객체를 ThreadLocal에 저장합니다.
다변량은 데이터 클래스 내에 ThreadLocal 클래스를 배치하는 것이 가장 좋습니다. 데이터 클래스는 싱글 톤 모드를 채택하므로 새 객체를 만들고 개체를 얻는 것이 더 편리하며 동시에 더 캡슐화됩니다.
package com.iot.thread; import java.util.random;/*** 2016/2/4에 Brian이 생성했습니다. */public class ThreadLocalTest {private static stroodlocal <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); stress.set (data); system.out.println (thread.currentthread ()+"put data :"+data); mythreadscopedata.getThreadInstance (). setName (stread.currentThread (). tostring ()); mythreadscopedata.getThreadinstance () a (). get (); new b (). get (); get ();}}). start ();}} static class a {public void get () {int data = strooms.get (); system.out.println ( "a"+thread.currentthread ()+"get data"+data); mythreadscopedata mythscopedata = mythreadscopedata.getthreadinstance (); system.out.println ( "a from"+mythreadscopedata);}} static class b {public void get () {int data = threadinger.get (); system.out.out.println ( "b from"+thread.currentthread ()+data); mythedata는 mythedata. mythreadscopedata.getthreadinstance (); system.out.println ( "b from"+mythreadscopedata);}}}/*** 데이터 클래스 캡슐화 multivariables* singleton mode, 내장 된 스레드 로컬 유형 변수*/classe mythreadscopedata {private mythreadscopedata ()} private strood <strichal <} data = new ThreadLocal <> (); public static mythreadscopedata getThreadInstance () {mythreadscopedata instance = data.get (); if (instance == null) {instance = new MythreadScopedata (); data.set (instance);} private string 이름; public setnam (public setname) {this.name = name;} public int getage () {return age;} public void setage (int age) {this.age = age;}@public string () {String reval = super.tostring () {이름, age} "+": { "+getname ()}}여러 가지 방법
마지막 방법의 예 :
5 스레드를 설계하고 J에 대해 매번 1 개의 스레드가 증가하고 다른 스레드는 J에 대해 매번 1 회 감소합니다.
Package com.iot.thread;/*** 2016/2/4에 Brian이 생성했습니다. */public class mutithreadsharedata {private static mutisharedata mutisharedata = new mutisharedata (); public static void main (string [] args) {for (int i = 0; i <3; i ++) {new Runnable () {@override public void run () {system.out.println (ride.curr. mutisharedata.getj ()+"+to :"+mutisharedata.increment ()+"}");}}). start ();} for (int i = 0; i <2; i ++) {new Runnable () {@override public void run () {system.out.println (Thread.currentthreadtthread ()+": {j j. "+mutisharedata.getj ()+" - to : "+mutisharedata.decrement ()+"} ");}}). start ();}}}}/** * 다른 객체에서 공유 데이터를 캡슐화하십시오 (데이터 조작 방법도 해당 객체에서 완료) */class mutisharedata {private int j = 0; 동기화 된 int retrement () {return --j;} public synchronized int getj () {return j;} public synchronized void setj (int j) {this.j = j;}}위의 내용은 다중 스레드 공유 데이터 코드를 프로그래밍하는 Java 프로그래밍에 대한 자세한 설명입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!