某技术群里群友抛出这样一个问题,我觉得挺有意思就写了一下。题目如下:
其实本质是一个生产者消费者问题,只不过他要求一共十个线程,id为奇数的是存钱,id为偶数的取钱。代码如下 可以直接运行。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class SyncMoney implements Runnable {
private int money = 0;
private List<Thread> threadList = new ArrayList<Thread>();
private final CountDownLatch countDownLatch = new CountDownLatch(1);
public SyncMoney() {
for (int i = 1; i <= 10; i++) {
Thread thread = new Thread(this);
threadList.add(thread);
thread.start();
}
}
/**
* 存钱,每次money++
*/
private synchronized void put() {
money++;
System.out.println(Thread.currentThread().getId() + ":存钱,余额" + money);
//暂停一会
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (money > 10) {
this.notify();
}
}
/**
* 取钱,每次money--。money不足10等待
*
* @throws InterruptedException
*/
private synchronized void get() {
while (money <= 10) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//暂停一会
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
money--;
System.err.println(Thread.currentThread().getId() + ":取钱,余额" + money);
}
/**
* 创建十个线程,启动任务
*/
public void start() {
countDownLatch.countDown();
}
@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
//奇数线程存钱,偶数线程取钱
long id = Thread.currentThread().getId();
if (id % 2 != 0) {
while (true) {
this.put();
}
} else {
while (true) {
this.get();
}
}
}
public static void main(String[] args) {
SyncMoney syncMoney = new SyncMoney();
syncMoney.start();
}
}
运行结果如下:
版权声明:本文为weixin_38965431原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。