线程执行器服务

时间:2014-01-29 15:13:31

标签: java threadpool executorservice

我的线程的start方法有问题,我不明白一切......

我给你看了代码:

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方法?

3 个答案:

答案 0 :(得分:2)

提交threadAction任务后,您需要使用executor.shutdown()关闭ExecutorService。这是为了确保线程不会继续运行。

您创建了一个大小为8的线程池,但您只提交了一个任务。您可以将ExecutorService更改为Executors.newSingleThreadExecutor(),或者在循环中将更多的threadAction实例提交给ExecutorService。

答案 1 :(得分:1)

如果您想迁移到ExecutorService,您必须至少改变两件事:

  1. 更改ThreadAction以实施Runnable,而不是扩展Thread
  2. 初始化操作后,将threadAction提交给ExecutorService实例:

    executor.submit(threadAction);
    

答案 2 :(得分:0)

First thing, you have to understand the role of ExecutorService. ExecutorService actually runs your thread and you need not have to call start method on the thread that you have created. In above code you have created thread but never submitted it to ExecutorService. Following example will help you to understand:

**

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

**