使用线程同时运行两个独立的任务
问题内容:
我已经研究了很多关于Java线程的教程,但是找不到答案。
我的问题是:如何同时运行两个独立的线程?
我的情况是:我有两个任务;
- 保存一些数据到数据库
- 在移动设备上发送推送通知。
由于这两个任务是独立的,因此我想同时执行它们。
我尝试使用具有两个线程的线程池,但是问题是数据库任务很快完成,但是发送推送通知需要一些时间。
因此,当一个任务完成而另一个任务仍未完成时,它将引发异常。
我的代码也没有问题,因为它不使用线程即可正常运行。
提前致谢
问题答案:
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);
并再次运行。你看到区别了吗?
这是控制执行者在处理队列时可以同时使用的线程数的方法。
组成更多任务,然后将它们添加到队列中,看看会得到什么。