Display images from web url in multi threading
I have 52 images that is coming from web URL.I want to display this images in multi threading process.
Can any one guide me how it is possible?????
I implement below code but its not working.
for (int i = 0; i <total_data; i++) {
GetBitmapClass getBitmapClass=new GetBitmapClass(i, image_path[i]);
if(Thread.activeCount()>14)
{
//System.out.println("Size "+pending_thread.size());
pending_thread.addElement(getBitmapClass);
}else
{
getBitmapClass.start();
}
}
//Thread class
class GetBitmapClass extends Thread
{
int index;
String url;
public GetBitmapClass(int index,String url)
{
this.index=index;
this.url=url;
}
public void run() {
// TODO Auto-generated method stub
StreamConnection stream = null;
InputStream in = null;
if(Thread.activeCount()>14)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Thread "+index+" Started \n count= "+Thread.activeCount());
try {
//stream = (StreamConnection) Connector.open(url+";deviceside=true;");
stream = (StreamConnection) Connector.open(url+";interface=wifi");
in = stream.openInputStream();
}
catch (Exception e) {
}
byte[] data = new byte[1024];
try {
DataBuffer db = new DataBuffer();
int chunk = 0;
while (-1 != (chunk = in.read(data))) {
db.write(data, 0, chunk);
}
in.close();
data = db.getArray();
} catch (Exception e) {
}
EncodedImage jpegPic = EncodedImage.createEncodedImage(data, 0,
data.length);
Bitmap bm = jpegPic.getBitmap();
bmp[index]=bm;
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
bitmapFields[index].setBitmap(bmp[index]);
gridFieldManager.add(bitmapFields[index]);
if((pending_thread.size()>0))
{
GetBitmapClass thread1=(GetBitmapClass)pending_thread.elementAt(0);
try
{
thread1.start();
pending_thread.removeElementAt(0);
}
catch (Exception e) {
// TODO: handle exception
System.out.print("Thread Not Started");
}
System.out.println("Size Reduce"+pending_thread.size());
}
System.out.print("Thread Completed"+index);
}
开发者_JS百科});
}
}
Thanks in advance.
I forgot to close stream connection. its required to close stream connection.
Trying to run a lot of threads at the same time is a bad idea for BB. This is not a desktop. Ususally you should avoid running more than one heavy background thread, otherwise you risk to slowdown your main UI thread to a level where users will stop using your app and call it "sluggish". Your threads are heavy - they resize images, do networking, manipulate Bitmaps. In order to fix this you need to create a list of Runnable
tasks and execute them on the only background thread. From my experience executing tasks sequentially is more efficient on BB than trying to run them all at once.
精彩评论