java在2007年的時候編寫過多線程爬蟲,當時對多線程的理解僅僅限於可以同時並發任務,對於多線程之間的調度,完全沒有理解。所以後來這的多線程的應用僅僅限於只能多線程並發任務。其實一切線上程中都可以被監控。
看下面的列子,我們來理解多線程之間如何進行控制的。
| 代碼如下 |
複製代碼 |
|
package com.javaer.thread;
public class PrintABC {
public static Boolean isThreadA = true;
public static Boolean isThreadB = false;
public static Boolean isThreadC = false;
public static void main(String[] args) {
final PrintABC abc = new PrintABC();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (abc) {
while (!isThreadA) {
try {
abc.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("A");
isThreadA = false;
isThreadB = true;
isThreadC = false;
abc.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (abc) {
while (!isThreadB) {
try {
abc.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("B");
isThreadA = false;
isThreadB = false;
isThreadC = true;
abc.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (abc) {
while (!isThreadC) {
try {
abc.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("C");
isThreadA = true;
isThreadB = false;
isThreadC = false;
abc.notifyAll();
}
}
}
}).start();
}
} |
輸出結果如下 :ABCABCABCABCABC
思路:解題思路大概是這樣的,開啟三個線程,每個線程一次列印一個字母,並且按照一定的順序列印,當列印A的時候,其他線程處於阻塞狀態,列印完A以後,將線程解鎖,讓列印B的那個線程開啟,其他線程處於阻塞狀態,同理列印C的時候,阻塞其他線程,這三個線程順序迴圈,就達到順序多次列印ABC的目的了。
這道題看似思路簡單,其實主要需要用到wait()方法和notify()方法,還有關鍵字synchronized,只有充分理解了這些,才能解出這道題。下面我有必要講解一下這兩個方法,還有關鍵字synchronized。
多線程並行下載的核心特點就是分段,並行下載。
比如一個檔案200M,分5個線程,那麼就給砍成5份,分別同時下就好了。速度當然比一點點下載來的要快的多。
| 代碼如下 |
複製代碼 |
|
package com.javaer.examples.file;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MyMutilDown {
/**
* 單線程的遠程下載
*/
public void SingleDown(String filePath, String url) {
try {
// 要寫入的檔案
File file = new File(filePath + getFileExtName(url));
FileWriter fWriter = new FileWriter(file);
URL ul = new URL(url);
URLConnection conn = ul.openConnection();
conn.setConnectTimeout(2000);// 請求逾時時間
// int len = conn.getContentLength();
InputStream in = conn.getInputStream();
// byte[] by = new byte[1024];
int temp = 0;
while ((temp = in.read()) != -1) {
System.out.println(temp);
fWriter.write(temp);
}
fWriter.close();
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 檔案尾碼名
*
* @param path
* @return
*/
public String getFileExtName(String path) {
return path.substring(path.lastIndexOf("."));
}
/**
* 測試多線程
*
* @param filePath
* 檔案儲存路徑
* @param url
* url
* @param tnum
* 線程數量
*/
public void MutiDown(String filePath, String url, int tnum) {
try {
// 要寫入的檔案
final File file = new File(filePath + getFileExtName(url));
System.out.println(file.getAbsolutePath());
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");// 建立隨機訪問
final URL ul = new URL(url);
HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
conn.setConnectTimeout(2000);// 請求逾時時間
conn.setRequestMethod("GET");
int len = conn.getContentLength();// 檔案長度
accessFile.setLength(len);
accessFile.close();
final int block = (len + tnum - 1) / tnum;// 每個線程下載的快大小
for (int i = 0; i < tnum; i++) {
final int a = i;
new Thread(new Runnable() {
int start = block * a;// 開始位置
int end = block * (a + 1) - 1;// 結束位置
@Override
public void run() {
HttpURLConnection conn2 = null;
RandomAccessFile accessFile2 = null;
InputStream in = null;
try {
conn2 = (HttpURLConnection) ul.openConnection();
conn2.setConnectTimeout(2000);// 請求逾時時間
conn2.setRequestMethod("GET");
// TODO Auto-generated method stub
conn2.setRequestProperty("Range", "bytes=" + start
+ "-" + end + "");// 設定一般請求屬性 範圍
in = conn2.getInputStream();
byte[] data = new byte[1024];
int len = 0;
accessFile2 = new RandomAccessFile(file, "rwd");
accessFile2.seek(start);
while ((len = in.read(data)) != -1) {
System.out.println(a + "/" + len);
accessFile2.write(data, 0, len);//並發寫入
}
System.out.println("線程:" + a + "下載完成!");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
accessFile2.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
MyMutilDown mydown = new MyMutilDown();
String path = "http://www.111cn.net/ openx-220080603.rar";
// mydown.SingleDown("/", path);
mydown.MutiDown("/bbc", path, 3);
}
} |
註明:本文著作權屬於ITeye會員 lohasle