zoukankan      html  css  js  c++  java
  • java使用Executor(执行器)管理线程

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

    class MyThread implements Runnable{
        private static int num = 0;
        @Override
        public void run() {
            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 class Main{
        public static void main(String[] args){
              ExecutorService exes = Executors.newCachedThreadPool();
              for(int i=0; i<5; ++i)
                  exes.execute(new MyThread());
              exes.shutdown();          
        }
    }

    2.FixedThreadPool()方法

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

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

    public class Main{
        public static void main(String[] args){
              ExecutorService exes = Executors.newFixedThreadPool(5);
              for(int i=0; i<6; ++i)
                      exes.execute(new MyThread());
              exes.shutdown();          
        }
    }

    3.newSingleThreadExecutor()方法

    public class Main{
        public static void main(String[] args){        
              ExecutorService exes = Executors.newSingleThreadExecutor();
              for(int i=0; i<5; ++i)
                  exes.execute(new MyThread());
              exes.shutdown();    
    }

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

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

    class MyThread implements Callable<String>{
        private static int num = 0;
        @Override
        public String call() throws Exception {
            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 class Main{
        public static void main(String[] args){
             ExecutorService exes = Executors.newCachedThreadPool();
             ArrayList<Future<String>> rets = new ArrayList<Future<String>>();
             for(int i=0; i<5; ++i)
                 rets.add(exes.submit(new MyThread()));
             for(Future<String> fs : 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 implements Runnable{
        private int priority;
        public MyThread(){
        }
        
        public MyThread(int priority){
            this.priority = priority;
        }
        
        private static int num = 0;
        private volatile double d;
        @Override
        public void run() {
            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 class Main{
        public static void main(String[] args){
             ExecutorService exes = Executors.newCachedThreadPool();
             for(int i=0; i<5; ++i)
                 exes.execute(new MyThread(Thread.MIN_PRIORITY));
             exes.execute(new MyThread(Thread.MAX_PRIORITY));
             exes.shutdown();
        }
    }

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

    四.后台线程

    class SimpleDaemons implements Runnable{
        @Override
        public void run() {
            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 class Main{
        public static void main(String[] args) throws InterruptedException{
             for(int i=0; i<10; ++i){
                 Thread daemon = new Thread(new SimpleDaemons());
                 daemon.setDaemon(true);
                 daemon.start();
             }
             System.out.println("All daemons started");
             TimeUnit.MILLISECONDS.sleep(1000);
        }
    }

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

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

    class DaemonThreadFactory implements ThreadFactory{
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    }
    class DaemonFromFactory implements Runnable{
        @Override
        public void run() {
            try{
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    
    public class Main{
        public static void main(String[] args) throws InterruptedException{
             ExecutorService exes = Executors.newCachedThreadPool(new DaemonThreadFactory());
             for(int i=0; i<5; ++i)
                     exes.execute(new DaemonFromFactory());
             System.out.println("All Daemos Started!");
             TimeUnit.MILLISECONDS.sleep(1000);
        }
    }
  • 相关阅读:
    多路复用与设置阻塞、非阻塞模式
    ['\xef\xbb\xbf这个什么含义? PY技术开发交流区 乐讯手机高手
    fcntl使用 and_tt 博客园
    Linux 设备驱动 Edition 3Linux设备驱动第三版(中文版)
    CRT source Google 搜索
    BOM–字节序标记 永不放弃的地盘 博客频道 CSDN.NET
    在C语言中,unsigned char是什么类型?_百度知道
    The JR Concurrent Programming Language
    C语言:为什么用fprintf(stderr,"Error");比printf("Error");更好?
    bash
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/5097470.html
Copyright © 2011-2022 走看看