简体   繁体   中英

How to suspend and resume a thread user input through the command prompt?

How to suspend and resume a thread user input through the command prompt?

I want a program where user can get the thread running from the stage where he stooped the thread by suspending.

package foo;

import java.util.Vector;

public class ThreadTest {

private Vector<String> threadNames = new Vector<String>();

public static void main(String[] args) {

    ThreadTest test = new ThreadTest();

    test.threadTest(Integer.parseInt(args[0]));

    System.out.println(test.threadNames);

}

private void threadTest(int numOfThreads) {

    Thread[] threads = new Thread[numOfThreads];

    for (int i = 0; i < threads.length; i++) {

        threads[i] = new foo.ThreadTest.MyThread();

        threads[i].start();

    }

    for (int i = 0; i < threads.length; i++) {

        try {

            threads[i].join();

        } catch (InterruptedException ignore) {}

    }

}

class MyThread extends Thread {

    public void run() {

        for (int i = 0; i < 1000000; i++) {

            i = i + 0;

        }

        threadNames.add(getName());

    }

}

}

You have a number of options. All will require some sort of RPC . The best approach will likely be based on JMX .

In particular, take a look at everything that is available on the ThreadMXBean (JMX). Now, this doesn't provide you the exact functions it sounds like you're looking for, but you could write your own that provides the extended functions you need.

Also, JMX is typically accessed through something like jconsole - which is GUI based. However, JMX is just an API, and you could write your own console-based client that exposes the functionality you require through CLI.

See also: calling java methods from a terminal

You could tackle this fairly simply with two threads?

  • Thread One would be responsible for listening to user input. On certain user inputs it would suspend or resume Thread Two
  • Thread Two would be responsible for any task which your want to be able to suspend and resume.

You also may want to take a look at the Java Concurrency Tutorials .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM