java简单实现多线程及线程池实例详解
发布于 2020-12-17|
复制链接
摘记: 本文为大家分享了java多线程的简单实现及线程池实例,供大家参考,具体内容如下一、多线程的两种实现方式1、继承Thread类的多线程
```java
/**
* 继承Thread类的多线程简单实现
*/
public class extThread extends Thr ..
本文为大家分享了java多线程的简单实现及线程池实例,供大家参考,具体内容如下一、多线程的两种实现方式1、继承Thread类的多线程
```java
/**
* 继承Thread类的多线程简单实现
*/
public class extThread extends Thread {
public void run(){
for(int i=0;i2、实现Runnable接口的多线程
```java
/**
* 实现runable接口的多线程实例
*/
public class runThread implements Runnable {
public void run(){
for(int i=0;i二、线程池的简单实现
```java
//实现Runnable接口
class TestThread implements Runnable{
public void run() {
for(int i = 0;i 三、java爬虫使用线程池实例
```java
/**
* 爬虫调度线程池
*/
public class threadPool {
public static HashMap statusMap = new HashMap();
// 存放爬虫,key为爬虫的id,value为爬虫的线程池
static HashMap threadMap = new HashMap();
//创建一个线程池
static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(200, 230,80000L,
TimeUnit.SECONDS,
new ArrayBlockingQueue(10),
new ThreadPoolExecutor.CallerRunsPolicy());
public static void executeThread(Spiders spider) {
statusMap.put(String.valueOf(spider.getId()), spider);
// 爬虫有效
if (spider.getFlag() == 0) {
if (spider.getStatus() == 0) {
// 表示爬虫进入抓取状态
ThreadPoolExecutor detailPool = null;
if (threadMap.get(spider.getId()) == null) {
detailPool = new ThreadPoolExecutor(30, 80, 80000L,
TimeUnit.SECONDS, new ArrayBlockingQueue(
10),
new ThreadPoolExecutor.CallerRunsPolicy());
threadMap.put(spider.getId(), detailPool);
threadPool.execute(new threadRun(spider, threadMap));
}
}
}
}
}
//实现Runnable接口
class threadRun implements Runnable {
private HashMap threadPoolMap;
private Spiders spider;
public threadRun(Spiders spider,
HashMap threadPoolMap) {
this.threadPoolMap = threadPoolMap;
this.spider = spider;
}
//线程执行体
public void run() {
try {
if ("rong360".equals(spider.getWebsite())) {
new RongThread(threadPoolMap.get(spider.getId()), spider)
.startSpider();
} else if ("xxgg_sd".equals(spider.getWebsite())) {
new Spider_ShanDong(threadPoolMap.get(spider
.getId()), spider).startSpider();
} else if ("xxgg_gz".equals(spider.getWebsite())) {
new Spider_GuiZhou(threadPoolMap.get(spider
.getId()), spider).startSpider();
} else if ("sx".equals(spider.getWebsite())) {
new SpiderSX(spider).startSpider();
} else if ("baidu".equals(spider.getWebsite())) {
new SpiderBaiDu(spider).startSpider();
} else if ("11315".equals(spider.getWebsite())) {
new Spider11315ByName(spider).startSpider();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```