线程的创建和线程池的使用

1、线程的几种创建方式

1.1继承Thread类重写run方法

public class ThreadPollExecutorTest {

    public static void main(String[] args){
        Thread thread = new MyThread();
        //线程的名字
        thread.setName("MyThread001111111");
        thread.start();
    }
    static class MyThread extends Thread{
        @Override
        public void run(){
            System.out.println(Thread.currentThread().getName()+",running,,,,,,,,,,");
        }
    }

}

1.2实现Runnable接口

public class RunnablTest {
    public static void main(String[] args){
        Thread thread = new Thread(new MyRunnable());
        thread.setName("myRunnable0001");
        thread.start();
    }

    static class MyRunnable implements Runnable{
        @Override
         public void run(){
            System.out.println("my runnable......");
        }
    }
}

1.3实现Callable接口通过FutureTask包装器来创建Thread线程

因为该接口可以返回一个结果,所以我们需要获取返回结果,这时系统提供了一个Future接口用于获取返回的结果,但是该接口代表的是一个异步计算的结果,所以我们需要等到计算完成时才能获取结果,否则就会一直阻塞直到结果返回。
所以我们获取结果要在调用isDone()方法返回true时才能调用get()方法。该接口有一个系统提供的实现类FutureTask,FutureTask类实现了RunnableFuture<V>,RunnableFuture<V>接口继承了Runnable, Future<V>两个接口。FutureTask中实现的Runnable中的run方法调用了Callable接口中的call方法。所以创建Callable接口的线程的方法与Runnable类似:

public class CallableTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "hello";
            }
        });

        Thread thread = new Thread(future);
        thread.setName("myCallable001");
        thread.start();
        while (!future.isDone()){
            try {
                System.out.println(thread.getName()+ " is not done");
                Thread.currentThread().sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        String result = future.get();
        System.out.println("result:"+result);
    }
}

2、线程池的使用

Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

2.1newCachedThreadPool
public static void main(String[] args) {  
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();  
        for (int i = 0; i < 10; i++) {  
            final int index = i;  
            try {  
                Thread.sleep(10);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            cachedThreadPool.execute(new Runnable() {  
                public void run() {  
                    System.out.println(index);  
                }  
            });  
        }  
    }
newFixedThreadPool
public static void main(String[] args) {  
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  
        for (int i = 0; i < 10; i++) {  
            final int index = i;  
            fixedThreadPool.execute(new Runnable() {  
                public void run() {  
                    try {  
                        System.out.println(index);  
                        Thread.sleep(10);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            });  
        }  
    }  
newScheduledThreadPool
public static void main(String[] args) {  
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
        for (int i = 0; i < 10; i++) {  
            scheduledThreadPool.schedule(new Runnable() {  
                public void run() {  
                    System.out.println("delay 3 seconds");  
                }  
            }, 3, TimeUnit.SECONDS);  
        }  
  
    }  
newSingleThreadExecitor
public static void main(String[] args) {  
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  
        for (int i = 0; i < 10; i++) {  
            final int index = i;  
            singleThreadExecutor.execute(new Runnable() {  
                public void run() {  
/*                  System.out.println(index);*/  
                    try {  
                        System.out.println(index);  
                        Thread.sleep(2000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            });  
        }  
    }  

Long
1 声望1 粉丝

一步,一步往上爬。