在上一篇《Android多線程研究(5)——線程之間共用資料》中對線程之間的資料共用進行了學習和研究,這一篇我們來看看如何解決多個線程之間的資料隔離問題,什麼是資料隔離呢?比如說我們現在開啟了兩個線程,這兩個線程都要同時給同一個全域變數data賦值,各個線程操作它賦值後的變數資料,這裡就需要用到隔離。先看一段代碼:
import java.util.Random; public class ThreadLocalTest { private static int data = 0; public static void main(String[] args) { for(int i=0; i<2; i++){ new Thread(new Runnable() { @Override public void run() { data = new Random().nextInt(); System.out.println(Thread.currentThread().getName() + " has put data: " + data); new A().get(); new B().get(); } }).start(); } } static class A{ public int get(){ System.out.println("A from " + Thread.currentThread().getName() + " has get data: " + data); return data; } } static class B{ public int get(){ System.out.println("B from " + Thread.currentThread().getName() + " has get data: " + data); return data; } } }
運行結果:
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/
從上面我們可以看到Thread-0和Thread-1都在操作變數data,但是兩個線程之間沒有做到對資料操作的隔離,所以輸出結果中兩個線程共用了一個data變數。
我們將上面代碼修改如下:
import java.util.HashMap; import java.util.Map; import java.util.Random; public class ThreadLocalTest { //private static int data = 0; private static Map<Thread, Integer> map = new HashMap<Thread, Integer>(); public static void main(String[] args) { for(int i=0; i<2; i++){ new Thread(new Runnable() { @Override public void run() { //data = new Random().nextInt(); int data = new Random().nextInt(); map.put(Thread.currentThread(), data); System.out.println(Thread.currentThread().getName() + " has put data: " + data); new A().get(); new B().get(); } }).start(); } } static class A{ public int get(){ System.out.println("A from " + Thread.currentThread().getName() + " has get data: " + map.get(Thread.currentThread())); return map.get(Thread.currentThread()); } } static class B{ public int get(){ System.out.println("B from " + Thread.currentThread().getName() + " has get data: " + map.get(Thread.currentThread())); return map.get(Thread.currentThread()); } } }