Java多線程數據共享可以通過以下幾種方式實現:
synchronized
關鍵字來確保多個線程對共享變量的訪問是同步的,避免出現線程安全問題。public class SharedData {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class MyThread implements Runnable {
private SharedData sharedData;
public MyThread(SharedData sharedData) {
this.sharedData = sharedData;
}
public void run() {
sharedData.increment();
}
}
public class Main {
public static void main(String[] args) {
SharedData sharedData = new SharedData();
Thread thread1 = new Thread(new MyThread(sharedData));
Thread thread2 = new Thread(new MyThread(sharedData));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sharedData.getCount());
}
}
synchronized
關鍵字來確保多個線程對共享對象的訪問是同步的。public class SharedObject {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class MyThread implements Runnable {
private SharedObject sharedObject;
public MyThread(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
sharedObject.increment();
}
}
public class Main {
public static void main(String[] args) {
SharedObject sharedObject = new SharedObject();
Thread thread1 = new Thread(new MyThread(sharedObject));
Thread thread2 = new Thread(new MyThread(sharedObject));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sharedObject.getCount());
}
}
Vector
、Hashtable
、ConcurrentHashMap
等。這些容器內部實現了同步機制,可以確保多個線程對容器的訪問是同步的。import java.util.concurrent.ConcurrentHashMap;
public class MyThread implements Runnable {
private ConcurrentHashMap<String, Integer> map;
public MyThread(ConcurrentHashMap<String, Integer> map) {
this.map = map;
}
public void run() {
map.put("count", map.get("count") + 1);
}
}
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("count", 0);
Thread thread1 = new Thread(new MyThread(map));
Thread thread2 = new Thread(new MyThread(map));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(map.get("count"));
}
}
需要注意的是,多線程數據共享可能會引發線程安全問題,因此需要采取合適的同步機制來確保數據的一致性和正確性。在Java中,常用的同步機制有synchronized
關鍵字、Lock
接口、volatile
關鍵字等。