簡體   English   中英

在單個線程中處理多個無限任務? PS一次運行一個任務,並從外部控制其任務行為(即啟動/停止任務)

[英]handle multiple infinite tasks in a single thread? P.S run one task at a time and control its task behavior(i.e starting/stoping task) from outside

我想制作一個包含3個無限任務的線程。

我希望一次運行一個任務,並在需要時啟動/停止運行任務。

例如,首先我要運行任務1,然后我要運行任務2,但是在停止任務1之后又再次要任務1運行,但是在停止任務2之后,依此類推。

無限任務需要檢查某些條件,如果滿足該條件,則執行某些操作;如果不滿足睡眠條件,則等待幾秒鍾;在喚醒后再執行上述相同操作。

無限可運行任務看起來像這樣:

new Runnable(){
    while(1){
         if(TaskQueue.getInstance().size()<= 100){
           TaskQueue.getInstance().push("add command to the end of queue");
         }else{
           try {
             Thread.sleep(10000);
           }catch (InterruptedException e) {
             e.printStackTrace();
           }
        }
     }     
 }

任何幫助,將不勝感激?

編輯:我修改了我的問題。 我想要一個連續的單個正在運行的線程(類似於looper)來監視3個無限任務,並從外部控制此單個連續的正在運行的線程任務。

將此用於實時啟動/停止線程:

 class MyThread extends Thread {

     private volatile boolean running = true; // Run unless told to pause

     ...

     @Override
     public void run() {

         // Only keep painting while "running" is true
         // This is a crude implementation of pausing the thread
         while (true) {
             if (Thread.currentThread().isInterrupted()) {
                 return;
             }
             if (running) {
                 //Your code
             } else yield;
         }

     }

     public void pauseThread() throws InterruptedException {
         running = false;
     }

     public void resumeThread() {
         running = true;
     }

 }

對於暫停線程,請使用以下命令:

myThread.pauseThread();

對於簡歷線程,請使用以下命令:

myThread.resumeThread();

對於停止線程,請使用以下命令(不推薦):

myThread.stop();

對於當前停止線程,請使用以下命令:

myThread.interrupt();

您必須使用類似Thread的類,該類已經實現了Runnable。

new Thread(){....};

它的工作方式是:

Thread t = new Thread(){.....};
t.start();
t.stop();

您還可以初始化一個新線程,例如:

Thread exampleThread = new thread();

之后,您可以通過以下任何方式在代碼中啟動它:

exampleThread.start();

您可以使用信號量來管理信號量。

private final static Semaphore semaphore = new Semaphore(0);


public static void main(String[] args) throws Exception {
    //入口
    threadTest();
}

public static void thread1() {
    try{
        //…… some code
    }
    finally{
        semaphore.release();
    }
}

public static void thread2() {
    semaphore.acquire(1);
}

謝謝,這是我的第一個答案。

我終於做了我的任務計划程序。 其API如下所示:

TaskScheduler taskScheduler = TaskScheduler.getInstance();
taskScheduler.startTaskOne();
taskScheduler.stopTaskOne();
taskScheduler.startTaskTwo();
taskScheduler.stopTaskTwo();

一次運行一個任務(因為我使用了Executors.newSingleThreadExecutor() )。 我們可以從外部控制任務的執行:

public class TaskScheduler {

    private static ExecutorService mTaskRunningService;
    private static TaskScheduler mInstance;
    private Future mFirstTaskFuture = null; 
    private Future mSecondTaskFuture = null;    


    static {
        configure();
    }

    private static void configure() {
        mTaskRunningService = Executors.newSingleThreadExecutor();
    }

    public static TaskScheduler getInstance() {
        if (mInstance == null) {
            mInstance = new TaskScheduler();
        }
        return mInstance;
    }


    private Runnable mTaskOneRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {

                    /** stop this single thread (i.e executing one task at time) service if this thread is interrupted
                     * from outside because documentation of {@link java.util.concurrent.ThreadPoolExecutor#shutdownNow()}
                     * says we need to do this*/
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    // task one work.......
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };


    private Runnable mTaskTwoRunnable = new Runnable() {
        @Override
        public void run() {

            try {
                while (true) {

                    /** stop this single thread (i.e executing one task at time) service if this thread is interrupted
                     * from outside because documentation of {@link java.util.concurrent.ThreadPoolExecutor#shutdownNow()}
                     * says we need to do this*/
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    // task two work......
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    public synchronized void startTaskOne() {
        if (mFirstTaskFuture == null) {
            // start executing runnable
            mFirstTaskFuture = mTaskRunningService.submit(mTaskOneRunnable);
        }
    }

    public synchronized boolean stopTaskOne() {
        if (mFirstTaskFuture != null) {

            // stop general reading thread
            mFirstTaskFuture.cancel(true);

            // cancel status
            boolean status = mFirstTaskFuture.isDone();

            // assign null because startTaskOne() again be called
            mGeneralFuture = null;

            return status;
        }
        return true;
    }

    public synchronized void startTaskTwo() {
        if (mSecondTaskFuture == null) {
            // start executing runnable
            mSecondTaskFuture = mTaskRunningService.submit(mTaskTwoRunnable);
        }
    }

    public synchronized boolean stopTaskTwo() {
        if (mSecondTaskFuture != null) {
            // clear task queue
            mTaskQueue.clearTaskQueue();

            // stop 22 probes reading thread
            mSecondTaskFuture.cancel(true);

            // cancel status
            boolean status = mSecondTaskFuture.isDone();

            // assign null because startTaskTwo() again be called
            mSecondTaskFuture = null;

            return status;
        }
        return true;
    }
}

暫無
暫無

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

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