java执行器是什么_java使用Executor(执行器)管理线程

一.一个实现了Runnable接口的类

class MyThread implementsRunnable{private static int num = 0;

@Overridepublic voidrun() {while(true){synchronized(MyThread.class){++num;try{

Thread.sleep(500);

}catch(Exception e){

System.out.println(e.toString());

}

System.out.println(Thread.currentThread().getName()+ " " +num);

}

}

}

}

1. newCachedThreadPool()方法

CacheThreadPool会为每一个任务创建一个线程。非常常见的情况是,单个的Executor被用来创建和管理系统中的任务。shutdown()方法可以防止新的任务被提交给这个Executor。如果在shutdown()方法之后提交新任务,则会抛出java.util.concurrent.RejectedExecutionException异常。

public classMain{public static voidmain(String[] args){

ExecutorService exes=Executors.newCachedThreadPool();for(int i=0; i<5; ++i)

exes.execute(newMyThread());

exes.shutdown();

}

}

2.FixedThreadPool()方法

FixedThreadPool使用了优先的线程集来执行所提交的任务。有了它,你就可以一次性预先执行代价高的线程分配。也就是说如果设置的最大线程数量是x,而提交的线程数y,那么(y-x)对应的这些线程要等到前x个线程执行完毕才会执行。

下面的例子中,线程6一直不会有机会执行。因为run()方法中是 while(true), 可以将while(true)去掉,前5个线程执行完毕后,才会执行第6个线程。

public classMain{public static voidmain(String[] args){

ExecutorService exes= Executors.newFixedThreadPool(5);for(int i=0; i<6; ++i)

exes.execute(newMyThread());

exes.shutdown();

}

}

3.newSingleThreadExecutor()方法

public classMain{public static voidmain(String[] args){

ExecutorService exes=Executors.newSingleThreadExecutor();for(int i=0; i<5; ++i)

exes.execute(newMyThread());

exes.shutdown();

}

SingleThreadExecutor就像是线程数量为1的FixedThreadPool。这对于你希望在另一个线程中连续运行的事物(长期存活的任务)来说,都是很有用的。如果想SingleThreadExecutor提交了多个任务,那么这些任务将排队,每个任务都会在下一个任务开始之前结束,所有的任务将使用相同的线程。

二.一个实现了Callable接口的类(从任务中产生返回值)

class MyThread implements Callable{private static int num = 0;

@Overridepublic String call() throwsException {for(int i=0; i<5; ++i){synchronized(MyThread.class){++num;

Thread.sleep(200);

System.out.println(Thread.currentThread().getName()+ " " +num);

}

}return Thread.currentThread().getName() + " success!";

}

}

1.ExecutorService.submit()方法

public classMain{public static voidmain(String[] args){

ExecutorService exes=Executors.newCachedThreadPool();

ArrayList> rets = new ArrayList>();for(int i=0; i<5; ++i)

rets.add(exes.submit(newMyThread()));for(Futurefs : rets){try{

System.out.println(fs.get());

}catch(InterruptedException e) {

e.printStackTrace();

}catch(ExecutionException e) {

e.printStackTrace();

}

}

}

}

submit()会产生Future对象,它用Callable返回结果的特定类型进行了参数化。可以调用Future的isDone()方法来查询Future是否已经完成。调用Future的get()方法来获取最终线程的执行结果。另外,Future的get()方法是一个阻塞方法,直到结果准备就绪。

三.线程的优先级

class MyThread implementsRunnable{private intpriority;publicMyThread(){

}public MyThread(intpriority){this.priority =priority;

}private static int num = 0;private volatile doubled;

@Overridepublic voidrun() {

Thread.currentThread().setPriority(priority);while(true){for(int i=0; i<100000; ++i){

d+= (Math.PI+Math.E)/(double)i;if(i%1000 == 0)

Thread.yield();

}synchronized(MyThread.class){++num;try{

Thread.sleep(500);

}catch(Exception e){

System.out.println(e.toString());

}

System.out.println(Thread.currentThread().getName()+ " " +num);

}

}

}

}public classMain{public static voidmain(String[] args){

ExecutorService exes=Executors.newCachedThreadPool();for(int i=0; i<5; ++i)

exes.execute(newMyThread(Thread.MIN_PRIORITY));

exes.execute(newMyThread(Thread.MAX_PRIORITY));

exes.shutdown();

}

}

volatile变量保证编译器对循环不进行任何的优化,如果不加入这些运算的话,就不会看到设置线程优先级的效果。数学运算是可以中断的,向控制台打印不能被中断。这里预案算时间足够的长,因此线程调度机制才来的及介入,交换任务并关注优先级,是的最高优先级被优先选择。

四.后台线程

class SimpleDaemons implementsRunnable{

@Overridepublic voidrun() {while(true){try{

TimeUnit.MILLISECONDS.sleep(200);

System.out.println(Thread.currentThread().getName());

}catch(InterruptedException e){

System.out.println(Thread.currentThread().getName()+ " : InterruptException!");

e.printStackTrace();

}

}

}

}public classMain{public static void main(String[] args) throwsInterruptedException{for(int i=0; i<10; ++i){

Thread daemon= new Thread(newSimpleDaemons());

daemon.setDaemon(true);

daemon.start();

}

System.out.println("All daemons started");

TimeUnit.MILLISECONDS.sleep(1000);

}

}

所谓后台线程,是指程序运行的时候在后台提供一种通用的服务的线程,并且这种线程并不属于程序中不可或缺的部分。因此,当所有的非后台线程结束时,程序也就终止了,同时会杀死进程中的所有的后台线程。反过来说,只要任何非后台线程还在运行,程序就不会终止。

通过定制自己的ThreadFactory, 可以定制有Executor创建的线程的属性(后台,优先级,名称)

class DaemonThreadFactory implementsThreadFactory{

@OverridepublicThread newThread(Runnable r) {

Thread t= newThread(r);

t.setDaemon(true);returnt;

}

}

class DaemonFromFactory implementsRunnable{

@Overridepublic voidrun() {try{

TimeUnit.MILLISECONDS.sleep(100);

System.out.println(Thread.currentThread().getName());

}catch(InterruptedException e){

e.printStackTrace();

}

}

}public classMain{public static void main(String[] args) throwsInterruptedException{

ExecutorService exes= Executors.newCachedThreadPool(newDaemonThreadFactory());for(int i=0; i<5; ++i)

exes.execute(newDaemonFromFactory());

System.out.println("All Daemos Started!");

TimeUnit.MILLISECONDS.sleep(1000);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值