之前做过阿里巴巴一个有关多线程的在线笔试题,题目大意是是一共有9个苹果,有两只猴子同时吃,一只猴子每次可以吃2个苹果,另外一只每次可以吃3个苹果,当苹果数量少于2个时,每次吃2个苹果的猴子则不能吃了,当苹果数量少于3个时,每次吃3个苹果的猴子则不能吃了。
这道题的解法很简单,就是开启两个线程,拿苹果的操作要加锁,本题用Lock来实现下:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyLockTest {
private static Integer num = 9;//苹果数量
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.lock();
try {
if(num >=2){
num = num -2;
System.out.println("猴子1吃了2个,还剩" + num + "个");
}else{
break;
}
} finally {
lock.unlock();
}
}
}
}.start();
new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.lock();
try {
if(num >=3){
num = num -3;
System.out.println("猴子2吃了3个,还剩" + num + "个");
}else{
break;
}
} finally {
lock.unlock();
}
}
}
}.start();
}
}