Thread td = new Thread(){
public void run(){
//do someting
Thread.sleep(1000);
///// do something
td.stop();
}
};
public static void main(String[] args){
//do someting this line
td.start();
/////do new someting this line
td.start();
}
当我开始计划时,我想要做1.> 2.> 2.1> 3。 →4 我是怎么做的
答案 0 :(得分:8)
stop()
,as documented已弃用,绝不应使用。一个线程只能启动一次(as documented as well):
多次启动线程永远不合法。
我建议您阅读Thread javadoc以及concurrency tutorial。
似乎你想在启动的线程中等待,直到在主线程中完成某些操作。您的描述过于模糊,无法给出明确的答案,但您应该查看java.util.concurrent
包中的Lock和CountDownLatch。
答案 1 :(得分:0)
use 'thread.sleep' or wait and notify
http://www.javatpoint.com/inter-thread-communication-example
答案 2 :(得分:0)
不推荐使用stop()但您可以实现此暂停并恢复功能,如下所示:
以下示例代码将给出线程暂停和恢复等行为:
public abstract class PausableTask implements Runnable{
private ExecutorService executor = Executors.newSingleThreadExecutor();
private Future<?> publisher;
protected volatile String state;
private void someJob() {
System.out.println("Job Done :- " + state);
}
abstract void task();
@Override
public void run() {
while(!Thread.currentThread().interrupted()){
task();
}
}
public void start(){
publisher = executor.submit(this);
state = "started";
}
public void pause() {
publisher.cancel(true);
state = "paused";
}
public void resume() {
// you won't see this state
state = "resumed";
start();
}
public void stop() {
state = "stoped";
executor.shutdownNow();
}
}
有关详细信息,请在此链接中提供更多示例代码:
http://handling-thread.blogspot.co.uk/2012/05/pause-and-resume-thread.html