【发布时间】:2015-04-22 09:36:27
【问题描述】:
想象一下下面的例子: 一个应用程序启动两个线程。 Provider 类持有并发集合并向其写入数据。消费者从集合中读取数据。
下面的代码是正确的还是我必须添加同步?
public class Application{
public static void main(String...args) throws Exception{
Provider p = new Provider();
new Thread(p).start();
new Thread(new Consumer(p)).start();
// Make sure the example stops after 60 seconds
Thread.sleep(1000*60);
System.exit(0);
}
}
/**The Provider (writes data to concurrent collection)*/
class Provider implements Runnable{
private ConcurrentMap<Integer, String> map
= new ConcurrentHashMap<Integer, String>(20, 0.5f, 1);
public void run(){
Integer i = 1;
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException ignore) {
}
// Synchronization ?
map.put(i, i.toString());
i++;
}
}
public ConcurrentMap<Integer, String> getMap(){
// Synchronization ?
return map;
}
}
/**The Consumer (reads data from concurrent collection)*/
class Consumer implements Runnable{
private Provider provider;
public Consumer(Provider p){
provider = p;
}
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
// Synchronization ?
ConcurrentMap<Integer, String> m = provider.getMap();
if(m!=null)
for(String s: m.values())
System.out.print(s);
System.out.println();
}
}
}
【问题讨论】:
标签: java collections concurrency