栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用线程同时运行两个独立的任务

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用线程同时运行两个独立的任务

new Thread(new Runnable() {    public void run() {        System.out.println("Look ma, no hands");    }}).start();new Thread(new Runnable() {    public void run() {        System.out.println("Look at me, look at me...");    }}).start();

效果很好…

我更喜欢个人使用ExecutorService。

使用ExecutorService示例进行了更新

所以我写了这个非常简单的例子…

基本上,它使用

ExecutorService
来运行几个简单的任务。就目前而言,这两个任务将彼此并行运行(同时)

public static void main(String[] args) throws InterruptedException {    ExecutorService service = Executors.newFixedThreadPool(2);    service.submit(new PathScanner());    service.submit(new Counter());    service.shutdown();    service.awaitTermination(1, TimeUnit.DAYS);    System.exit(0);}public static class PathScanner implements Callable<Object> {    @Override    public Object call() throws Exception {        scan(new File("C:/"), 0);        return null;    }    protected void scan(File path, int deepth) {        if (deepth < 15) { System.out.println("Scanning " + path + " at a deepth of " + deepth); File[] files = path.listFiles(); for (File file : files) {     if (file.isDirectory()) {         scan(file, ++deepth);     } }        }    }}public static class Counter implements Callable<Object> {    @Override    public Object call() throws Exception {        for (int index = 0; index < 1000; index++) { Thread.sleep(1); System.out.println(index);        }        return null;    }}

运行…

现在更改

ExecutorService service =Executors.newFixedThreadPool(2);
ExecutorService service =Executors.newFixedThreadPool(1);
并再次运行。你看到区别了吗?

这是控制执行者在处理队列时可以同时使用的线程数的方法。

组成更多任务,然后将它们添加到队列中,看看会得到什么。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569808.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号