簡體   English   中英

使用線程同時運行兩個獨立的任務

[英]Running two independent tasks simultaneously using threads

我已經在java中學習了很多關於線程的教程,但我找不到答案。

我的問題是:如何同時運行兩個獨立的線程?

我的情況是:我有兩個任務;

  1. 將一些數據保存到數據庫中
  2. 在移動設備上發送推送通知。

由於這兩個任務是獨立的,我想同時執行它們。

我嘗試使用具有兩個線程的線程池,但問題是數據庫任務很快完成,但發送推送通知需要一些時間。

因此,當一個任務完成而另一個任務仍處於未決狀態時,它會拋出異常。

我的代碼也沒有問題,因為它運行正常而不使用線程。

提前致謝

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); to ExecutorService service = Executors.newFixedThreadPool(1); 並再次運行它。 你看到了區別嗎?

這是控制執行程序在處理隊列時可以使用的同時線程數的方法。

補充更多任務並將其添加到隊列中,看看你得到了什么。

我有一個用例,使用多線程搜索多個文件夾中的文件。 作為輸入,我只有根目錄路徑,並且可以有任意數量的子目錄。 假設 - 文件將始終僅在其中一個子目錄中可用。

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SearchFile implements Runnable {

    private String dirPath = null;

    public SearchFile() {

    }

    public SearchFile(String dirPath) {
        this.dirPath = dirPath;
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        File dir = new File("D://");
        checkRootDirectory(dir);
        long endTime = System.currentTimeMillis();
        System.out.println("Time taken: "+(endTime - startTime) + "ms");
    }

    private static void checkRootDirectory(File root) {
        File[] list = root.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() && !pathname.isHidden();
            }
        });

        ExecutorService service = Executors.newFixedThreadPool(list.length);
        for (File directories : list) {
            String dirPath = directories.getAbsolutePath();
            Thread thread = new Thread(new SearchFile(dirPath));
            service.execute(thread);
        }
        service.shutdown();
        while(!service.isTerminated()) {

        }
    }

    @Override
    public void run() {
        checkEachDirectory(new File(dirPath), "Temp.txt");
    }

    private void checkEachDirectory(File root, String fileName) {
        File[] list = root.listFiles();
        if (null != list) {
            for (File dir : list) {
                if (dir.isDirectory()) {
                    checkEachDirectory(dir, fileName);
                } else if (fileName.equalsIgnoreCase(dir.getName())) {
                    System.out.println(
                            "Thread name: " + Thread.currentThread().getName() + " Founded @" + dir.getAbsolutePath());
                }
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM