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);并再次运行。你看到区别了吗?
这是控制执行者在处理队列时可以同时使用的线程数的方法。
组成更多任务,然后将它们添加到队列中,看看会得到什么。



