java多线程

来源:互联网 发布:尼尔森数据怎么拉取 编辑:程序博客网 时间:2024/06/18 18:19

1. execute(Runnable)

并行的访问,异步

public class MyTest {    Long mockGet(long id) {        System.out.println("id: " + id);        Thread thread = Thread.currentThread();        //System.out.println("Thread: " + thread);        //System.out.println("Thread Id: " + thread.getId());        System.out.println("Thread Name: " + thread.getName());        //System.out.println("Thread Group: " + thread.getThreadGroup());        //System.out.println("Thread Priority: " + thread.getPriority());        try {            Thread.sleep(5000);            System.out.println("finish sleep");        } catch (InterruptedException e) {            e.printStackTrace();        }        return id * 100;    }    @Test    public void testThread() {        ExecutorService executorService = Executors.newFixedThreadPool(10);        List<Long> input = Arrays.asList(1L, 2L, 3L, 4L, 5L);        for (long item : input) {            executorService.execute(new Runnable() {                public void run() {                    System.out.println("Asynchronous task : " + mockGet(item));                }            });        }        System.out.println("test async"); // 瞬间执行,异步        try {            Thread.sleep(20000); // 主线程若退出,则程序结束。sleep及run()都执行不到        } catch (InterruptedException e) {            e.printStackTrace();        }        executorService.shutdown();    }}

2. submit(Runnable)

并行,异步,阻塞, 可拿到返回值

public class MyTest {    Long mockGet(long id) {        System.out.println("id: " + id);        Thread thread = Thread.currentThread();        //System.out.println("Thread: " + thread);        //System.out.println("Thread Id: " + thread.getId());        System.out.println("Thread Name: " + thread.getName());        //System.out.println("Thread Group: " + thread.getThreadGroup());        //System.out.println("Thread Priority: " + thread.getPriority());        try {            Thread.sleep(5000);            System.out.println("finish sleep");        } catch (InterruptedException e) {            e.printStackTrace();        }        return id * 100;    }    @Test    public void testThread() {        ExecutorService executorService = Executors.newFixedThreadPool(10);        List<Long> input = Arrays.asList(1L, 2L, 3L, 4L, 5L);        List<Future> res = new ArrayList<>();        for (long item : input) {            Future future = executorService.submit(new Runnable() {                public void run() {                    System.out.println("Asynchronous task : " + mockGet(item));                }            });            res.add(future);        }        System.out.println("test async"); // 这句立即打印,不需要等sleep 5s。 异步        for (Future future : res) {            try {                System.out.println("future.get()=" + future.get());            } catch (InterruptedException e) {                e.printStackTrace();            } catch (ExecutionException e) {                e.printStackTrace();            }        }        executorService.shutdown();    }}

首先5个线程都输出
id: 1
Thread Name: pool-1-thread-1
然后2s后,输出:
Asynchronous task : 500
future.get()=null
返回null表示成功执行完毕

3. submit(Callable)

和submit(runnable)基本一样,区别是这个future.get()可以返回自定义的结果.
并行的,异步,future.get()仍然是阻塞的

public class MyTest {    Long mockGet(long id) {        System.out.println("id: " + id);        Thread thread = Thread.currentThread();        //System.out.println("Thread: " + thread);        //System.out.println("Thread Id: " + thread.getId());        System.out.println("Thread Name: " + thread.getName());        //System.out.println("Thread Group: " + thread.getThreadGroup());        //System.out.println("Thread Priority: " + thread.getPriority());        try {            Thread.sleep(5000);            System.out.println("finish sleep");        } catch (InterruptedException e) {            e.printStackTrace();        }        return id * 100;    }    @Test    public void testThread() {        ExecutorService executorService = Executors.newFixedThreadPool(10);        List<Long> input = Arrays.asList(1L, 2L, 3L, 4L, 5L);        List<Future> res = new ArrayList<>();        for (long item : input) {            Future future = executorService.submit(new Callable(){                public Object call() throws Exception {                    long curRes = mockGet(item);                    System.out.println("Asynchronous Callable : " + curRes);                    return curRes;                }            });            res.add(future);        }        System.out.println("test async"); // 这句立即打印,不需要等sleep 5s。 异步        for (Future future : res) {            try {                System.out.println("future.get()=" + future.get());            } catch (InterruptedException e) {                e.printStackTrace();            } catch (ExecutionException e) {                e.printStackTrace();            }        }        executorService.shutdown();    }}

输出为:
id: 1
Thread Name: pool-1-thread-1
。。。 2s后。。。
Asynchronous Callable : 500
future.get()=100

4. invokeall

同步阻塞的形式,可以通过Future.get()得到返回值

public class MyTest {
Long mockGet(long id) {
System.out.println(“id: ” + id);
Thread thread = Thread.currentThread();
//System.out.println(“Thread: ” + thread);
//System.out.println(“Thread Id: ” + thread.getId());
System.out.println(“Thread Name: ” + thread.getName());
//System.out.println(“Thread Group: ” + thread.getThreadGroup());
//System.out.println(“Thread Priority: ” + thread.getPriority());
try {
Thread.sleep(5000);
System.out.println(“finish sleep”);
} catch (InterruptedException e) {
e.printStackTrace();
}
return id * 100;
}

@Testpublic void testThread() {    ExecutorService executorService = Executors.newFixedThreadPool(10);    Set<Callable<String>> callables = new HashSet<Callable<String>>();    callables.add(new Callable<String>() {        public String call() throws Exception {            return "Task 1 : " + mockGet(1L);        }    });    callables.add(new Callable<String>() {        public String call() throws Exception {            return "Task 2 : " + mockGet(2L);        }    });    callables.add(new Callable<String>() {        public String call() throws Exception {            throw new NullPointerException();            //return "Task 3 : " + mockGet(3L);        }    });    List<Future<String>> res = null;    try {        res = executorService.invokeAll(callables);    } catch (Exception e) {    }    System.out.println("test async"); // 这句需要等sleep 5s完了才打印。同步    for (Future<String> curRes : res) {        try {            System.out.println("Future.get=" + curRes.get());        } catch (Exception ex) {        }    }    executorService.shutdown();}

}