如何自动重启一个被困的java程序

时间:2017-10-22 11:33:47

标签: java restart

我有一个程序A,它使用方法execute()运行,并且每次迭代它在一个txt文件上写一个String。有时这个程序阻塞,我需要停止它,只需回忆一下知道从哪里重新启动的方法execute()。我有一个扩展Thread的程序B,它与A并行运行,如果程序A被阻塞,则每隔X次验证一次,但我不知道如何阻止对象A并用自己的方法重新启动它。最简单的方法是什么?

P.S。程序A卡住不是因为我是一个糟糕的程序员(我是出于其他原因),而是因为它适用于不允许我做我想做的在线服务。

1 个答案:

答案 0 :(得分:0)

您可以使用Condition并等待条件在保护线程中的指定时间段内满足。如果条件花费太长时间,保护线程将收到InterruptedException

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    private static class PotentiallyBlockingTask implements Runnable {
        private final Lock lock;
        private final Condition condition;

        public PotentiallyBlockingTask(Lock lock, Condition condition) {
            this.lock = Objects.requireNonNull(lock);
            this.condition = Objects.requireNonNull(condition);
        }

        @Override
        public void run() {         
            // run the task

            // signal the guard thread that it is done.
            lock.lock();            
            try {
                condition.signal();
            }   finally {
                lock.unlock();
            }
        }
    }

private static class GuardTask implements Runnable {
    private final Lock lock;
    private final Condition condition;

    public GuardTask(Lock lock, Condition condition) {
        this.lock = Objects.requireNonNull(lock);
        this.condition = Objects.requireNonNull(condition);
    }

    public void run() {
        lock.lock();
        try {
            condition.await(30, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // handle situation
        } finally {
            lock.unlock();
        }
    }
}

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        PotentiallyBlockingTask pbt = new PotentiallyBlockingTask(lock, condition);
        GuardTask gt = new GuardTask(lock, condition);
    //....
    }
}