Java多线程同步问题:实例演示
在Java中,多线程同步是通过多种机制来保证不同线程对共享资源的正确访问。下面我们将通过一个简单的例子来展示这些同步机制。
示例代码:
```java
// 创建共享变量
public class SharedVariable {
private int count = 0;public synchronized int getCount() {
return count++;
}
}
// 创建多个线程
class Producer extends Thread {
private SharedVariable shared;
public Producer(SharedVariable shared) {
this.shared = shared;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
shared.getCount(); // 省略实际操作
if (i == 5) { // 模拟暂停
Thread.sleep(100);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer extends Thread {
private SharedVariable shared;
public Consumer(SharedVariable shared) {
this.shared = shared;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
if (shared.getCount() == 5) { // 模拟同步条件
System.out.println("同步:Producer暂停,Consumer获取到最新值 " + shared.getCount());
break;
}
System.out.println("Producer执行:值 " + shared.getCount()); // 执行实际操作
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
SharedVariable shared = new SharedVariable();
Producer producer = new Producer(shared);
Consumer consumer = new Consumer(shared);
producer.start(); // 启动生产者线程
consumer.start(); // 启动消费者线程
try {
producer.join(); // 等待生产者线程结束
consumer.join(); // 等待消费者线程结束
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
- 演示结果:
在这个例子中,我们创建了一个共享变量SharedVariable
,以及两个线程:生产者Producer
和消费者Consumer
。
- 生产者会增加共享变量的计数。
- 消费者会在同步条件满足时(即计数为5),获取到最新值,并打印出来。
通过这个例子,我们可以看到Java多线程中的synchronized关键字如何实现同步。
还没有评论,来说两句吧...