如何重新启动一个线程 [英] how to restart a thread

查看:174
本文介绍了如何重新启动一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写一个文件监视器,如果附加了一个新行,它将检查文件,监视器实际上是一个线程,它将一直读取randomaccessfile的行。

I tried to write a file monitor which will check the file if a new line is appended,the monitor in fact is a thread which will read the line by a randomaccessfile all the time.

这是监控核心代码:

public class Monitor {
    public static Logger                                    log             = Logger.getLogger(Monitor.class);
    public static final Monitor             instance        = new Monitor();
    private static final ArrayList<Listener>    registers       = new ArrayList<Listener>();

    private Runnable                                        task            = new MonitorTask();
    private Thread                                          monitorThread   = new Thread(task);
    private boolean                                         beStart         = true;

    private static RandomAccessFile                         raf             = null;
    private File                                            monitoredFile   = null;
    private long                                            lastPos;

    public void register(File f, Listener listener) {
        this.monitoredFile = f;
        registers.add(listener);
        monitorThread.start();
    }

    public void replaceFile(File newFileToBeMonitored) {
        this.monitoredFile = newFileToBeMonitored;

        // here,how to restart the monitorThread?
    }

    private void setRandomFile() {
        if (!monitoredFile.exists()) {
            log.warn("File [" + monitoredFile.getAbsolutePath()
                    + "] not exist,will try again after 30 seconds");
            try {
                Thread.sleep(30 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            setRandomFile();
            return;
        }
        try {
            if (raf != null) {
                raf.close();
                lastPos = 0;
            }
            raf = new RandomAccessFile(monitoredFile, "r");
            log.info("monitor file " + monitoredFile.getAbsolutePath());
        } catch (FileNotFoundException e) {
            // The file must exist now
        } catch (IOException e) {}
    }

    private void startRead() {
        beStart = true;
        String line;
        while (beStart) {
            try {
                raf.seek(lastPos);
                while ((line = raf.readLine()) != null) {
                    fireEvent(new FileEvent(monitoredFile.getAbsolutePath(),
                            line));
                }
                lastPos = raf.getFilePointer();
            } catch (IOException e1) {}
        }
    }

    private void stopRead() {
        this.beStart = false;
    }

    private void fireEvent(FileEvent event) {
        for (Listener lis : registers) {
            lis.lineAppended(event);
        }
    }

    private class MonitorTask implements Runnable {
        @Override
        public void run() {
            stopRead();

            //why putting the resetReandomAccessFile in this thread method is that it will sleep if the file not exist.
            setRandomFile();
            startRead();
        }

    }

}

这是一些帮助类:

public interface Listener {
    void lineAppended(FileEvent event);
}


public class FileEvent {
    private String  line;
    private String  source;

    public FileEvent(String filepath, String addedLine) {
        this.line = addedLine;
        this.source = filepath;
    }
    //getter and setter

}

这是调用监视器的示例:

And this is a example to call the monitor:

public class Client implements Listener {
    private static File f   = new File("D:/ab.txt");

    public static void main(String[] args) {
        Monitor.instance.register(f, new Client());
        System.out.println(" I am done in the main method");
        try {
            Thread.sleep(5000);
            Monitor.instance.replaceFile(new File("D:/new.txt"));
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void lineAppended(FileEvent event) {
        String line = event.getLine();
        if (line.length() <= 0)
            return;
        System.err.println("found in listener:" + line + ":" + line.length());
    }
}

现在,我的问题是代码工作得很好如果我只需调用:

Now,my probelm is the code work well if I just call:

Monitor.instance.register(file,listener);

这将监视文件的行追加,并通知听众。

This will monitor the file for line appending,and will notify the listener.

然而,当我调用时,它不起作用:

However it does not work when I call the :

Monitor.instance.replaceFile(anotherfile);

这意味着我想监视另一个文件,而不是之前。

This means I want to monitor another file rather than before.

所以在我的监视器中我必须重新启动线程,如何制作它?

So in my Monitor I have to restart the thread,how to make it?

我试过了:

monitorThread.interruppt();

它不会贬值。

任何人可以帮我解决或告诉我该怎么办?

Anyone can fix it for me or tell me how to do ?

谢谢。

在我问之前,我有谷歌搜索重启java线程,所以我知道一个无法重启死线程,但我的线程没有返回,所以我认为它可以重新启动。

Before I ask,I have googling the "restart java thread",so I know one can not restart a dead thread,but my thread does not return,so I think it can be restarted.

推荐答案

我只是编写了一个骨架示例而不是解释。我没有很好地测试它,但它可能有一些用处。

Instead of explaining, I just coded up a skeleton example. I did not test it terribly well, but it may be of some use.

为了监控(另一个)文件,只需创建一个新的监视器,传递给它ScheduledExecutorService的。启动和停止监控非常简单。您可以(应该)为多个监视器重用相同的执行程序。

In order to monitor a(nother) file, just create a new Monitor, passing it a ScheduledExecutorService. Starting and stopping monitoring is straightforward. You can (should) reuse the same executor for multiple monitors.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public interface Event
{
}

public interface Listener
{
    void handle(Event event);
}

public class Monitor
{
    private static final int CHECK_EVERY_SECONDS = 10;
    private static final int RECHECK_AFTER_IF_NOT_EXISTS_SECONDS = 30;

    private File file;
    private ScheduledExecutorService executor;
    private boolean active;
    private List<Listener> listeners;

    public Monitor(File file, ScheduledExecutorService executor)
    {
        super();
        this.file = file;
        this.executor = executor;
        listeners = new ArrayList<Listener>();
    }

    public synchronized void start()
    {
        if (active)
        {
            return;
        }
        active = true;
        executor.execute(new Runnable()
        {
            public void run()
            {
                synchronized (Monitor.this)
                {
                    if (!active)
                    {
                        System.out.println("not active");
                        return;
                    }
                }
                if (!file.exists())
                {
                    System.out.println("does not exist, rescheduled");
                    executor.schedule(this, RECHECK_AFTER_IF_NOT_EXISTS_SECONDS, TimeUnit.SECONDS);
                    return;
                }
                Event event = doStuff(file);
                System.out.println("generated " + event);
                updateListeners(event);
                System.out.println("updated listeners and rescheduled");
                executor.schedule(this, CHECK_EVERY_SECONDS, TimeUnit.SECONDS);
            }
        });
    }

    private Event doStuff(final File file)
    {
        return new Event()
        {
            public String toString()
            {
                return "event for " + file;
            }
        };
    }

    public synchronized void stop()
    {
        active = false;
    }

    public void addListener(Listener listener)
    {
        synchronized (listeners)
        {
            listeners.add(listener);
        }
    }

    public void removeListener(Listener listener)
    {
        synchronized (listeners)
        {
            listeners.remove(listener);
        }
    }

    private void updateListeners(Event event)
    {
        synchronized (listeners)
        {
            for (Listener listener : listeners)
            {
                listener.handle(event);
            }
        }
    }

    public static void main(String[] args) throws IOException
    {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
        File file = new File("test.png");
        Monitor monitor = new Monitor(file, executor);
        monitor.addListener(new Listener()
        {
            public void handle(Event event)
            {
                System.out.println("handling " + event);
            }
        });
        monitor.start();
        System.out.println("started...");
        System.in.read();       
        monitor.stop();
        System.out.println("done");
        executor.shutdown();
    }

}

这篇关于如何重新启动一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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