Java多线程同步问题:实例演示
在Java中,多线程的同步主要通过synchronized关键字、wait/notify机制和Lock接口实现。
以下是一个简单的多线程同步问题实例演示:
使用synchronized关键字:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
在这个例子中,我们创建了一个Counter类,它有一个count变量。我们使用synchronized关键字对increment方法和getCount方法进行了同步。
使用wait/notify机制:
public class WaitNotifyExample {
private final Object lock = new Object();
public void producer() {
while (true) {
synchronized (lock) {
if (count == 10) { // 目标已达到,生产者线程进入等待状态
lock.wait();
break;
} else {
count++;
System.out.println("Producer: " + count);
lock.notifyAll(); // 生产者线程唤醒所有等待它的线程
break;
}
}
}
}
public void consumer() {
while (true) {
try {
Thread.sleep(1000); // 消费者线程每秒执行一次操作
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
if (count == 10) { // 目标已达到,消费者线程进入等待状态
System.out.println("Consumer: Wait for producer's signal");
lock.wait();
break;
} else {
count--;
System.out.println("Consumer: " + count);
lock.notifyAll(); // 消费者线程唤醒所有等待它的线程
break;
}
}
}
}
public static void main(String[] args) {
WaitNotifyExample example = new WaitNotifyExample();
Thread producerThread = new Thread(example::producer);
Thread consumerThread = new Thread(example::consumer);
producerThread.start(); // 生产者线程启动
consumerThread.start(); // 消费者线程启动
try {
producerThread.join(); // 等待生产者线程完成
consumerThread.join(); // 等待消费者线程完成
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们创建了一个Counter类,并通过wait/notify机制实现线程间的同步。当count达到10时,生产者和消费者都会进入等待状态,直到计数器发生变化。
还没有评论,来说两句吧...