- 問題設計: 用多個線程同時從網上爬書,爬下來的書使用一個線程作為插入,這些線程共用同一個書籍隊列,並且同時開始運行
書籍POJO
1 package thread; 2 3 public class Book { 4 private Integer bookId; 5 private String bookName; 6 7 public Integer getBookId() { 8 return bookId; 9 }10 11 public void setBookId(Integer bookId) {12 this.bookId = bookId;13 }14 15 public String getBookName() {16 return bookName;17 }18 19 public void setBookName(String bookName) {20 this.bookName = bookName;21 }22 }
爬蟲線程
1 package thread; 2 3 import java.util.List; 4 import java.util.Queue; 5 6 public class CrawlerThread extends Thread { 7 private List<Integer> bookIdList; //待爬書籍的Id號 8 private Queue<Book> bookQueue; //爬完書籍的共用儲存隊列 9 10 public CrawlerThread(List<Integer> bookIdList, Queue<Book> bookQueue) {11 this.bookIdList = bookIdList;12 this.bookQueue = bookQueue;13 }14 15 public void run() {16 for(int i = 0; i < bookIdList.size(); i++) {17 Book book = new Book(); //把這兩步當做爬蟲爬書的過程18 book.setBookId(bookIdList.get(i));19 book.setBookName("書名" + book.getBookId());20 21 try {22 sleep((long) (Math.random() * 1000 * 1000)); //隨機sleep 100 - 1000 秒,類比爬蟲爬書時的延時過程23 } catch (InterruptedException e) {24 e.printStackTrace();25 }26 27 bookQueue.offer(book); //爬完的書籍插入共用隊列28 }29 }30 }
插入線程
1 package thread; 2 3 import java.util.Queue; 4 5 public class InsertThread extends Thread { 6 private Queue<Book> bookQueue; //爬完書籍的共用儲存隊列 7 8 public InsertThread(Queue<Book> bookQueue) { 9 this.bookQueue = bookQueue;10 }11 12 public void run() {13 int timer = 0; //逾時計時器14 15 while(timer < 30) { //如果連續30分鐘bookQueue均為空白,則逾時,線程結束16 if(bookQueue.size() != 0) { //如果隊列不為空白17 Book book;18 while((book = bookQueue.poll()) != null) {19 System.out.println(book.getBookName()); //把這步當成插入資料庫吧20 }21 timer = 0; //逾時計時器清零22 } else {23 try {24 sleep(60 * 1000); //等待爬蟲一分鐘25 } catch (InterruptedException e) {26 e.printStackTrace();27 }28 timer++; //timer時間+129 }30 }31 }32 }
主程式
1 package thread; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.Queue; 6 import java.util.concurrent.ConcurrentLinkedQueue; 7 8 public class Start { 9 public void main(String[] args) {10 Queue<Book> bookQueue = new ConcurrentLinkedQueue<Book>(); //使用安全執行緒的隊列作為共用書籍隊列11 12 //構造待爬書籍Id號13 List<Integer> bookIdList = new ArrayList<Integer>();14 bookIdList.add(1);15 bookIdList.add(2);16 bookIdList.add(3);17 bookIdList.add(4);18 bookIdList.add(5);19 20 CrawlerThread ct = new CrawlerThread(bookIdList, bookQueue); //此處你可以將Id列表分為多分,分配給多個線程爬,我就不寫了,懶..- -21 InsertThread it = new InsertThread(bookQueue); //插入資料庫線程22 23 ct.start();24 it.start();25 }26 }