簡體   English   中英

線程執行器服務

[英]Thread executorservice

我的線程的啟動方法有問題,我不明白一切......

我給你看了代碼:

public class ThreadAction extends Thread{

    @Override
public void run() {
    ActionFactory factory = new ActionFactory();
    IAction action;
    for (int i = 0; i < list.size(); i++) {
        action = factory.getIAction(list.get(i));
        action.setFile(file);
        try {
            // Creates a random access file stream to read from, and
            // optionally to write to
            channel = new RandomAccessFile(file, "r").getChannel();
            // We put a lock on the file
            lock = channel.tryLock(0, file.length(), true);
            // after the file has been locked, we can send it
            action.send();
            // after the file has been sent, we move it in a temporary
            // repository specified in the configuration file
            lock.release();
            channel.close();
            Path location = Paths.get(file.getPath());
            Path destination = Paths.get(temp);
            Files.move(location, destination);
        } catch (IOException e) {
            logger.error("message", e);
            // e.printStackTrace();
        } catch (OverlappingFileLockException e) {
            logger.error("message", e);
            e.printStackTrace();
        } catch (SendException e) {
            try {
                lock.release();
                channel.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                logger.error("message", e1);
                // e1.printStackTrace();
            }
        }
    }
}

}

我在這里使用我的線程與thread.start(),但我想使用executorService來限制我的線程數,但當我嘗試使用它沒有任何反應!

void init() {
    for (Directory dir : configuration.directoriesList) {
        list(dir);
    }
}

void list(Directory dir) {
    File directory = new File(dir.path);
    File[] fList = directory.listFiles();
    ExecutorService executor = Executors.newFixedThreadPool(8);
    if (fList != null) {
        for (File f : fList) {
            if (f.isFile()) {
                ArrayList<IConfig> configList = getActions(f, "ENTRY_CREATE", getDirectoriesList(f), getMatchList(f, getDirectoriesList(f)));
                // implement new thread with the good parameters
                threadAction = new ThreadAction();
                threadAction.setList(configList);
                threadAction.setEvent("ENTRY_CREATE");
                threadAction.setFile(f);
                threadAction.setTemp(temp + "//" + f.getName());
                threadAction.start();
            } else if (f.isDirectory()) {
                list(new Directory(f.getAbsolutePath(), true));
            }
        }
    }

}

如果你知道為什么沒有發生......我想是因為我現在不使用start方法?

提交threadAction任務后,您需要使用executor.shutdown()關閉ExecutorService。 這是為了確保線程不會繼續運行。

您創建了一個大小為8的線程池,但您只提交了一個任務。 您可以將ExecutorService更改為Executors.newSingleThreadExecutor(),也可以在循環中將更多的threadAction實例提交給ExecutorService。

如果要遷移到ExecutorService ,則必須至少更改兩件事:

  1. 更改ThreadAction以實現Runnable而不是擴展Thread
  2. 初始化操作后,將threadAction提交到ExecutorService實例:

     executor.submit(threadAction); 

首先,您必須了解ExecutorService的作用。 ExecutorService實際上運行你的線程,你不必在你創建的線程上調用start方法。 在上面的代碼中,您創建了線程,但從未將其提交給ExecutorService。 以下示例將幫助您了解:

**

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
    public class ExecutorServiceCheck {
        public static Integer sum(int j) {
              int result=0;
              for(int i =0; i<10; i++) {
                  result= result+i;
              }
               return result;   



        }


        public static void main(String[] args) {
            final ExecutorServiceCheck obj = new ExecutorServiceCheck();
            Thread t1 = new Thread(new AddHelper());

            ExecutorService service = Executors.newFixedThreadPool(8);
            service.submit(t1);

        }
    }
    class AddHelper implements Runnable {
        public void run() {
            System.out.println(ExecutorServiceCheck.sum(13));
        }
    }

**

暫無
暫無

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

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