本文介绍了在单个线程中处理多个无限任务? PS一次运行一个任务并从外部控制其任务行为(即启动/停止任务)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个包含3个无限任务的线程.

I want to make a single thread which would contain 3 infinite tasks.

我希望一次运行一个任务,并在需要时启动/停止运行任务.

I want one task to run at a time and start/stop running task when required.

例如,首先我要运行任务1,然后我要运行任务2,但在停止任务1之后又再次要任务1运行,但在任务2停止之后,依此类推.

For example first I want task 1 to run, then I want task 2 to run but after stopping task 1 and again I want task 1 to run but after stopping of task 2 and so on.

无限任务需要检查某些条件,如果满足该条件,请执行一些操作;如果不满足睡眠条件,请等待几秒钟,然后在唤醒后再次执行上述相同操作.

Infinite task needs to check some condition and if that condition is satisfied perform some operations and if not satisfied sleep for few seconds and after wake up perform the above same operations again.

无限可运行任务看起来像这样:

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个无限任务,并从外部控制这个连续的单线程运行任务.

Edit : I modified my question. I want a continuous single running thread(some thing like looper ) to monitor 3 infinite tasks and control this single continuous running thread tasks from outside.

推荐答案

将此用于实时启动/停止线程:

Use this for start/stop thread in real-time:

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

 }

对于暂停线程,请使用此:

For pause thread use this:

myThread.pauseThread();

对于恢复线程,请使用此:

For resume thread use this:

myThread.resumeThread();

对于停止线程,请使用此(不推荐):

For stop thread use this (Not recommended):

myThread.stop();

对于当前停止的线程,请使用此:

For currently stop thread use this:

myThread.interrupt();

这篇关于在单个线程中处理多个无限任务? PS一次运行一个任务并从外部控制其任务行为(即启动/停止任务)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 10:45