多线程同步问题:Java应用示例
在Java中,多线程同步主要是通过各种锁(如synchronized关键字、ReentrantLock等)和并发工具类(如CountDownLatch、Semaphore等)来实现的。
以下是一个简单的Java多线程同步示例,使用了synchronized关键字:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int value() {
return count;
}
}
// 示例:两个线程交替增加计数器
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.increment();
try {
// 控制线程等待,模拟资源限制
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
Thread thread2 = new Thread(() -> {
for (int i = 5; i < 10; i++) {
counter.increment();
try {
// 控制线程等待,模拟资源限制
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
thread1.start();
thread2.start();
// 等待两个线程执行完毕
thread1.join();
thread2.join();
System.out.println("Final count: " + counter.value());
}
}
在这个示例中,我们创建了一个Counter类,并使用synchronized关键字来确保在任何时候只有一个线程可以访问increment()
和value()
方法。这样就实现了多线程的同步。
还没有评论,来说两句吧...