题目:线程A负责实时往Map里put 1-100的数字,线程B负责实时从这个map中get数字并进行累加
(A放入MAP一个值后,B取出来,然后A继续放,B继续取,以此循环一直到A放完100,B取完100,结束),
B实时打印当前时刻累加的结果。
代码:
package com.ncarzone.fastsearch.biz.facade.service;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<Integer,Integer> map = new HashMap();
Object lock = new Object();
final Status status = new Status();
status.setLock(false);
Thread threadA = new Thread(new Runnable(){
@Override
public void run(){
int i = 0;
while(i<100){
synchronized(lock){
if (status.isLock()){
try {
lock.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
} else {
i++;
map.put(i,i);
status.setLock(true);
lock.notifyAll();
}
}
}
}
});
Thread threadB = new Thread(new Runnable(){
@Override
public void run(){
int i = 0;
int num = 0;
while(i<100){
synchronized(lock){
if (status.isLock()){
i++;
num = num + map.get(i);
System.out.println("累加:"+ num);
status.setLock(false);
lock.notifyAll();
} else {
try {
lock.wait();
}catch(Exception e){
}
}
}
}
}
});
threadA.start();
threadB.start();
}
}
public class Status{
private boolean Lock;
public boolean isLock() {
return Lock;
}
public String setLock(boolean lock) {
Lock = lock;
return null;
}
}