下面是我使用的图像线程的示例,每次有图像显示时都会调用它。我使用类似于此的代码来执行其他网络连接。 这个问题,我怀疑我的表演问题,是我缺乏线程池。创建一个线程池来处理网络连接
如果这些线程中的多个或多个线程在完成之前创建,它们是不是同时存在,总是会降低性能?
我该如何实现Thread Pooling?我已经看到了这个词汇,但我没有找到一个很好的简单实例。
public class ImageThread extends Thread {
private String url;
private HttpConnection httpConn;
private InputStream is;
private JSONArray array;
private Bitmap image;
private ImageThreadCallback c;
private static boolean hasImageCache = false;
private static MultiMap imageCache;
public ImageThread(String url, ImageThreadCallback c, String ident){
System.out.println("Connection begin!");
this.url = url;
this.c = c;
}
public void notifyUs(){
this.c.update(image);
}
public void run(){
myConnectionFactory connFact = new myConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
System.out.println("Connection factory!");
if(connDesc != null)
{
System.out.println("Connection not null!");
httpConn = (HttpConnection) connDesc.getConnection();
try {
httpConn.setRequestMethod(HttpConnection.GET);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
is = null;
try
{
final int iResponseCode = httpConn.getResponseCode();
System.out.println("Connection in run!");
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) httpConn;
try {
is = inputConn.openInputStream();
System.out.println("Connection got inputstream!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = null;
try {
data = IOUtilities.streamToBytes(is);
System.out.println("Connection got data!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EncodedImage hai = EncodedImage.createEncodedImage(data, 0, data.length);
image = hai.getBitmap();
notifyUs();
}
catch(IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
}
除了线程池,有没有什么问题与我的代码?我通过创建这样的线程避免了ui事件线程?
我不认为这是可用于黑莓。是否有可能将每个图像下载作为TimerTask运行并将其添加到Timer对象,该对象是单个线程并会自动对其进行排队?我发现这是另一篇文章的解决方案,但我不确定这是否是一种可接受的方法。 – Adam
@Adam这可能是一个解决方案,但我还没有使用它。除此之外,如果黑莓手机只有一个或两个内核(如今大多数手机一样),创造更多2线程可能已经损害了性能。因此,使用队列和单个线程下载图像可能是一个好主意。 – Thomas
您提到了connectionFactory的单个实例。我会在应用程序加载时实例化吗?我将如何使它适用于我所有的线程和类。对不起,这个查询可能是java 101. – Adam