For example, I have a lot of pictures sheets.
http://www.xx.com/1.jpg
http://www.xx.com/2.jpg
http://www.xx.com/3.jpg
http://www.xx.com/4.jpg
http://www.xx.com/5.jpg
.................. 100.jpg
names of these pictures are digital growth .
I now want to do is : two threads. While to download.
class MultiDownloadThread implements Runnable{
private int index;
public void run() {
// TODO Auto-generated method stub
synchronized (this) {
index++;
download(index);//这个方法,里面会有堵塞,
}
}
class Demo{
public static void main(String []args){
MultiDownloadThread t=new MultiDownloadThread();
new Thread(t).start();
new Thread(t).start();
}
}
want this, start two threads , but you can download 2 . Respectively to download
1.jpg, 2.jpg;
3.jpg, 4.jpg;
5.jpg, 6.jpg;
but not, if the thread enters a download, the second thread must wait because the synchronized block , download pictures to wait for the network .
question how done , sync to get index + +, then the synchronized block (synchronized) start out download (index);
The general requirement is that the two threads acquire synchronization logo (index + +), and then were to perform a blocking download method (download (index))
------ Solution ----- ---------------------------------------
In fact, I did not understand the case of multi-core how to make two threads to run simultaneously
------ For reference only ---------------------------------- -----
should not ah , the landlord would like to achieve this functionality before I specifically did .
multithreaded indeed a little faster than the single-threaded , but just a little bit faster , because the most important thing is to see bandwidth. . .
landlord only needs to index the entire process without the need for locking locked . .
landlord to set up a
synchronized int addIndex () {
return index + +;
}
methods
public void run () {
/ / TODO Auto-generated method stub
int i = addIndex ();
download (i) ;/ / This should be a
}
------ For reference only ----------------------------- ----------
thanks , has been the question , thank you. Solved
没有评论:
发表评论