在Java中,可以通過以下幾種方式實現多線程同步:
synchronized關鍵字可以用于修飾方法或者代碼塊,當一個線程訪問被synchronized修飾的方法或代碼塊時,其他線程將無法訪問該方法或代碼塊。這樣可以確保同一時間只有一個線程能夠訪問共享資源。
示例:
public class SynchronizedExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increase();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increase();
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter: " + counter.getCount());
}
}
class Counter {
private int count;
public synchronized void increase() {
count++;
}
public synchronized int getCount() {
return count;
}
}
Java提供了Lock接口和ReentrantLock類來實現更靈活的線程同步。與synchronized相比,Lock提供了更高的靈活性,例如可以嘗試獲取鎖、定時獲取鎖和可中斷獲取鎖等操作。
示例:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increase();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increase();
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter: " + counter.getCount());
}
}
class Counter {
private int count;
private Lock lock = new ReentrantLock();
public void increase() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
Java提供了許多高級的同步工具,如Semaphore、CountDownLatch、CyclicBarrier等。這些工具可以幫助您更容易地實現復雜的多線程同步需求。
示例(使用CountDownLatch):
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
Counter counter = new Counter();
CountDownLatch latch = new CountDownLatch(2);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increase();
}
latch.countDown();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increase();
}
latch.countDown();
}
});
t1.start();
t2.start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter: " + counter.getCount());
}
}
class Counter {
private int count;
public synchronized void increase() {
count++;
}
public synchronized int getCount() {
return count;
}
}
以上就是Java中實現多線程同步的幾種方法。在實際應用中,可以根據具體需求選擇合適的同步方式。