多线程并发访问全局变量引起空指针有关问题
多线程并发访问全局变量引起空指针问题
执行过程中会出现空指针,求教什么原因啊?
------解决方案--------------------
最后当你调用以下语句的时候,就会出现NPE了
package com.lee.picCommon;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lee.control.Client;
public class PicDownUpdate{
private static final Log logger = LogFactory.getLog(Client.class);
public static byte[] downloadForHttp(String imageUrl) throws Exception {
URL url = new URL(imageUrl);
//打开网络输入流
DataInputStream dis = new DataInputStream(url.openStream());
byte[] img = readInputStream(dis);
return img;
}
public static byte[] downloadForFtp(String imageUrl){
return null;
}
public static byte[] readInputStream(InputStream inputStream)throws Exception{
byte[]buffer=new byte[1024]; //设置缓冲区
int len = -1;
ByteArrayOutputStream outSteam=new ByteArrayOutputStream();
while((len=inputStream.read(buffer))!= -1){
outSteam.write(buffer,0,len);
}
outSteam.close();
inputStream.close();
return outSteam.toByteArray();
}
public static byte[] startUp(String oId,String url,String module){
byte[] img = null;
try {
if(module.toUpperCase().equals("HTTP")){
img = downloadForHttp(url);
}else if(module.toUpperCase().equals("FTP")){
img = downloadForFtp(url);
}
} catch (Exception e) {
System.out.println("> URL:["+url+"] 无法连接,ID:["+oId+"]!!!");
logger.error("URL:["+url+"] 无法连接,ID:["+oId+"]!!!");
}
return img;
}
public static List<Map> listss = new ArrayList<Map>();
public synchronized Map getMap(){
if(listss.size()==0){
return null;
}else{
return listss.remove(0);
}
}
class Test implements Runnable{
public void run() {
while(true){
Map m = getMap();
String url = m.get("URL").toString();
String id = m.get("ID").toString();
if(m != null){
try {
// byte[] b = downloadForHttp(url);
System.out.println("更新成功...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
for(int i=0;i<10000;i++){
Map map = new HashMap();
map.put("ID", i);
map.put("URL", "http://www.baidu.com");
listss.add(map);
}
new PicDownUpdate().start();
}
public void start(){
for(int i=0;i<8;i++){
new Thread(new Test()).start();
}
}
}
执行过程中会出现空指针,求教什么原因啊?
------解决方案--------------------
public synchronized Map getMap(){
if(listss.size()==0){
return null;
}else{
return listss.remove(0); // 这里的remove会使得共享的listss一直减少到到0个元素,这样就返回了null
}
}
最后当你调用以下语句的时候,就会出现NPE了
Map m = getMap(); // 这里得到的m已经是null了
String url = m.get("URL").toString(); // NPE会发生