在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中实现多线程同步的几种方法。在实际应用中,可以根据具体需求选择合适的同步方式。