使用线程同时运行两个独立任务 [英] Running two independent tasks simultaneously using threads

查看:116
本文介绍了使用线程同时运行两个独立任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中研究过很多关于线程的教程,但我找不到答案。



我的问题是:如何同时运行两个独立的线程?



我的情况是:我有两个任务;


  1. 将一些数据保存到数据库

  2. 在移动设备上发送推送通知。

由于这两项任务是独立的,我想同时执行它们。



我尝试使用带有两个线程的线程池,但问题是数据库任务很快完成,但发送推送通知需要一些时间。



因此,当一个任务完成而另一个任务仍未决时,它会抛出异常。



我的代码也没有问题,因为它运行正常而不使用线程。



提前致谢

解决方案

  new Thread(new Runnable(){
public void run(){
System.out.println(look ma,no hands);
}
}) 。开始();

new Thread(new Runnable(){
public void run(){
System.out.println(看着我,看着我......);
}
})。start();

工作得很好......



我个人更喜欢使用 ExecutorService 。 / p>

使用ExecutorService示例更新



所以我写了这个非常快的例子......



基本上它使用 ExecutorService 来运行一些简单的任务。就目前而言,两个任务将彼此并行运行(同时)

  public static void main(String [] args)抛出InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
service.submit(new PathScanner());
service.submit(new Counter());

service.shutdown();
service.awaitTermination(1,TimeUnit.DAYS);

System.exit(0);
}

公共静态类PathScanner实现Callable< Object> {

@Override
public Object call()抛出异常{
scan(new File(C:/),0);
返回null;
}

protected void scan(文件路径,int深度){
if(deepth< 15){
System.out.println(Scanning+路径+深度为+深度);

File [] files = path.listFiles();
for(文件文件:files){
if(file.isDirectory()){
scan(file,++ deepth);
}
}
}
}
}

公共静态类计数器实现Callable< Object> {

@Override
public Object call()抛出异常{
for(int index = 0; index< 1000; index ++){
Thread.sleep( 1);
System.out.println(index);
}
返回null;
}
}

运行它...



现在更改 ExecutorService service = Executors.newFixedThreadPool(2); to ExecutorService service = Executors.newFixedThreadPool(1) ; 并再次运行它。您是否看到了区别?



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



组成更多任务并将它们添加到队列中,看看你得到了什么。


I've studied lots of tutorials on threads in java but I'm unable to find my answer.

My question is: how to run two independent threads simultaneously?

My case is: I have two tasks;

  1. save some data to the database
  2. send a push notification on a mobile device.

Since these two tasks are independent I want to execute them simultaneously.

I tried using a thread pool with two threads but the problem is that the database tasks finishes quickly but it takes some time to send a push notification.

Consequently when one task is finished while the other is still pending, it throws an exception.

Also there is no problem in my code because it runs fine without using threads.

Thanks in advance

解决方案

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();

Works just fine...

I'd prefer the use of an ExecutorService personally.

UPDATED with ExecutorService example

So I wrote this really quick example...

Basically it uses an ExecutorService to run a couple of simple tasks. As it stands, both task will run in parallel with each other (simultaneously)

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;
    }
}

Run it...

Now change ExecutorService service = Executors.newFixedThreadPool(2); to ExecutorService service = Executors.newFixedThreadPool(1); and run it again. Did you see the difference?

This is the way to control the number of simultaneously threads that executor can use while processing it's queue.

Make up some more tasks and add them to the queue and see what you get.

这篇关于使用线程同时运行两个独立任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆