尊旭网
当前位置: 尊旭网 > 知识 >

threadpoolexecutor

时间:2024-03-01 23:58:05 编辑:阿旭

JAVA ThreadPoolExecutor 线程池如何控制活动线程的执行时间,例如该线程执行时间超过30秒就自动终止

在线程开始的时候,用一个变量记录当前系统时间,线程执行完后再取一次系统时间,两个时间的差就是线程执行时间了。


这个类你参考一下
java.util.Timer

用这下面的TimeTask类(指定延时)

java里面的sleep()并不能精确定时,TimeTask可以:例下面的小程序:

import java.util.*;
public class test{
public static void main (String []args){
Timer timer=new Timer();//实例化Timer类
timer.schedule(new TimerTask(){
public void run(){
System.out.println("退出");
this.cancel();}},30000);//这里百毫秒
System.out.println("本程序存在30秒后自动退出");
}
}


ThreadPoolExecutor线程池?

当我们需要实现并发、异步等操作时,可以使用ThreadPoolExecutor。ThreadPoolExecutor线程池:系统中,我们创建(extend Thread/implement Runnable)、销毁(正常run方法完成后线程终止)线程的代价是比较高昂的。如果频繁地创建和销毁进程,会大大降低系统运行效率和吞吐量。线程池使得线程可以被复用,避免了线程频繁创建和销毁的开销,提高系统的运行效率和吞吐量。实例ThreadPoolExecutor.execute(new Runnable () {});相关概念:Task任务:new Runnable () {}任务就是一个Runnable的对象,任务的执行方法就是该对象的run方法。缓冲队列:workQueue一个阻塞队列。BlockingQueue workQueue;corePoolSize:核心线程数核心线程会一直存活,即使没有任务需要执行。当线程数小于核心线程数时(还未满,就会一直增),即使有线程空闲,线程池也会优先创建新线程处理。maxPoolSize:最大线程数当线程数大于corePoolSize,且任务队列已满时。线程池会创建新线程来处理任务,直到线程数量达到maxPoolSize。execute(Runnable)通过execute将一个任务交由线程池管理。当一个任务通过execute方法欲添加到线程池时,线程池采用的策略如下(即添加任务的策略):1、如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。2、如果此时线程池中的数量等于corePoolSize,但是缓冲队列workQueue未满,那么任务被放入缓冲队列。3、如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。4、如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过handler所指定的策略来处理此任务。如下图:希望对您有所帮助!~

使用spring 的 ThreadPoolTaskExecutor 线程池,怎样移除任务

使用spring 的 ThreadPoolTaskExecutor 线程池,怎样移除任务呢?回答1://添加线程池任务ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();Runnable task = new RunnableTask();threadPool.execute(task);//移除任务threadPool.getThreadPoolExecutor().remove(task);回答2:引用来自“keyer”的答案 //添加线程池任务ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();Runnable task = new RunnableTask();threadPool.execute(task);//移除任务threadPool.getThreadPoolExecutor().remove(task); 移除不了啊。总是返回false回答3:/*** Removes this task from the executor's internal queue if it is* present, thus causing it not to be run if it has not already* started.** This method may be useful as one part of a cancellation* scheme. It may fail to remove tasks that have been converted* into other forms before being placed on the internal queue. For* example, a task entered using submit might be* converted into a form that maintains Future status.* However, in such cases, method {@linkThreadPoolExecutor#purge}* may be used to remove those Futures that have been cancelled.** @param task the task to remove* @return true if the task was removed*/public boolean remove(Runnable task) {return getQueue().remove(task);} 这个是源码注释,你自己看下吧。


线程池超过等待队列继续加任务会怎么样

用线程池编写多线程程序时,当所有任务完成时,要做一些统计的工作。而统计工作必须要在所有任务完成才能做。所以要让主线程等待所有任务完成。可以使用ThreadPoolExecutor.awaitTermination(long timeout, TimeUnit unit)。请看示例代码:
package com.chenlb;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* 线程池使用示例, 主线程等待所有任务完成再结束.
*
* @author chenlb 2008-12-2 上午10:31:03
*/
public class ThreadPoolUse {

public static class MyTask implements Runnable {
private static int id = 0;

private String name = "task-"+(++id);
private int sleep;

public MyTask(int sleep) {
super();
this.sleep = sleep;
}

public void run() {
System.out.println(name+" -----start-----");
try {
Thread.sleep(sleep); //模拟任务执行.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" -----end "+sleep+"-----");
}

}

public static void main(String[] args) {
System.out.println("==================start==================");
ThreadPoolExecutor executor = new ThreadPoolExecutor(5,5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue());
int n = 10;
int sleep = 10 * 1000; //10s
Random rm = new Random();
for(int i=0; i<n; i++) {
executor.execute(new MyTask(rm.nextInt(sleep)+1));
}

executor.shutdown();//只是不能再提交新任务,等待执行的任务不受影响

try {
boolean loop = true;
do { //等待所有任务完成
loop = !executor.awaitTermination(2, TimeUnit.SECONDS); //阻塞,直到线程池里所有任务结束
} while(loop);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("==================end====================");
}

}
当然还有其它方法。

http://xtu-xiaoxin.iteye.com/blog/649677


shutDown()

当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态。此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。但是,此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。 唯一的影响就是不能再提交任务了,正则执行的任务即使在阻塞着也不会结束,在排队的任务也不会取消。

shutdownNow()

根据JDK文档描述,大致意思是:执行该方法,线程池的状态立刻变成STOP状态,并试图停止所有正在执行的线程,不再处理还在池队列中等待的任务,当然,它会返回那些未执行的任务。
它试图终止线程的方法是通过调用Thread.interrupt()方法来实现的,但是大家知道,这种方法的作用有限,如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以,ShutdownNow()并不代表线程池就一定立即就能退出,它可能必须要等待所有正在执行的任务都执行完成了才能退出。

上面对shutDown()以及shutDownNow()作了一个简单的、理论上的分析。如果想知道why,则需要亲自打开JDK源码,分析分析。
想要分析shutDown()以及shutDownNow()源码,我建议首先要对ThreadPoolExecutor有个大概了解。因为关闭线程池的所有方法逻辑都在ThreadPoolExecutor中处理的。


java怎么实现线程

java实现线程常用到的方法有三种,供参考:/** * 方法一:继承Thread类 * * @author qd * */public class MyThread extends Thread { @Override public void run() { System.out.println("run方法里面编写业务代码"); } public static void main(String[] args) { MyThread myThread = new MyThread(); // 调用start方法启动线程 myThread.start(); MyThread1 myThread1 = new MyThread1(); Thread thread = new Thread(myThread1); // 调用start方法启动线程 thread.start(); }}/** * 方法二:实现Runnable接口 * * @author qd * */class MyThread1 implements Runnable { @Override public void run() { System.out.println("run方法里面编写业务代码"); }}/** * 方法三:实现Callable接口 优点:可以传参数,有返回值类型 * * @author qd * */class MyThread2 implements Callable { @Override public Integer call() throws Exception { return null; }}


java中线程有几种状态图解

1. NEW, 这个最简单了,

static void NEW() {
Thread t = new Thread ();
System. out.println(t.getState());
}

输出NEW

2. RUNNABLE, 也简单, 让一个thread start, 同时代码里面不要sleep或者wait等

private static void RUNNABLE() {
Thread t = new Thread(){

public void run(){
for(int i=0; i<Integer.MAX_VALUE; i++){
System. out.println(i);
}
}

};

t.start();
}

3. BLOCKED, 这个就必须至少两个线程以上, 然后互相等待synchronized 块

private static void BLOCKED() {

final Object lock = new Object();

Runnable run = new Runnable() {

@Override
public void run() {
for(int i=0; i<Integer.MAX_VALUE; i++){

synchronized (lock) {
System. out.println(i);
}

}
}
};

Thread t1 = new Thread(run);
t1.setName( “t1”);
4. WAITING, 这个需要用到生产者消费者模型, 当生产者生产过慢的时候, 消费者就会等待生产者的下一次notify

private static void WAITING() {

final Object lock = new Object();
Thread t1 = new Thread(){
@Override
public void run() {

int i = 0;

while(true ){
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
}
System. out.println(i++);
}
}
}
};

Thread t2 = new Thread(){
@Override
public void run() {

while(true ){
synchronized (lock) {
for(int i = 0; i< 10000000; i++){
System. out.println(i);
}
lock.notifyAll();
}

}
}
};
Thread t2 = new Thread(run);
5. TIMED_WAITING, 这个仅需要在4的基础上, 在wait方法加上一个时间参数进行限制就OK了.

把4中的synchronized 块改成如下就可以了.

synchronized (lock) {
try {
lock.wait(60 * 1000L);
} catch (InterruptedException e) {
}
System. out .println(i++);
}
t2.setName( “t2”);

t1.start();
t2.start();

}

6. TERMINATED, 这个状态只要线程结束了run方法, 就会进入了…

private static void TERMINATED() {
Thread t1 = new Thread();
t1.start();
System. out.println(t1.getState());
try {
Thread. sleep(1000L);
} catch (InterruptedException e) {
}
System. out.println(t1.getState());
}