gpt4 book ai didi

Java 线程挂起不起作用

转载 作者:行者123 更新时间:2023-11-30 06:10:40 26 4
gpt4 key购买 nike

这是一个使用java线程的示例代码。问题是我无法暂停线程。

public class RunnableDemo implements Runnable {
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
while (true) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronized(this) {
while(suspended) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
public void suspend() {
suspended = true;
}

下面的挂起函数不起作用:

RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
R1.suspend(); // This line does not work and thread continues ...

事实上,当我调用 suspend() 时,线程看不到 suspended 的新值。有什么想法吗?

最佳答案

suspended声明为volatile :

volatile boolean suspended = false;

关于Java 线程挂起不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com