Java多執行緒之執行緒範圍內共享變數的概念與作用
阿新 • • 發佈:2019-02-19
要實現執行緒範圍內的資料共享,就是說不管是A模組還是B模組,如果它們現在在同一個執行緒上執行,它們操作的資料應該是同一個,下面的做法就不行:
package javaplay.thread.test; import java.util.Random; public class ThreadScopeShareData { 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 void get() { System.out.println("A from " + Thread.currentThread().getName() + " get data : " + data); } } static class B { public void get() { System.out.println("B from " + Thread.currentThread().getName() + " get data : " + data); } } }
output:
Thread-0 has put data : 840132982
Thread-1 has put data : -1767656158
A from Thread-0 get data : -1767656158
A from Thread-1 get data : -1767656158
B from Thread-0 get data : -1767656158
B from Thread-1 get data : -1767656158
在這個執行緒範圍內,不管哪個模組去取這個變數拿到的都是同一個變數;換了另外一個執行緒就是另外一份資料了;即執行緒內共享,執行緒外獨立;
package javaplay.thread.test; import java.util.HashMap; import java.util.Map; import java.util.Random; public class ThreadScopeShareData { private static int data = 0; private static Map<Thread, Integer> threadData = 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() { int data = new Random().nextInt(); System.out.println(Thread.currentThread().getName() + " has put data : " + data); threadData.put(Thread.currentThread(), 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().getName() + " get data : " + data); } } static class B { public void get() { int data = threadData.get(Thread.currentThread()); System.out.println("B from " + Thread.currentThread().getName() + " get data : " + data); } } }
output:
Thread-0 has put data : -74463225
Thread-1 has put data : -2119679267
A from Thread-1 get data : -2119679267
A from Thread-0 get data : -74463225
B from Thread-1 get data : -2119679267
B from Thread-0 get data : -74463225
資料庫的連線就是一個典型的應用