gpt4 book ai didi

java - 从方法中中断线程

转载 作者:行者123 更新时间:2023-12-01 18:13:02 26 4
gpt4 key购买 nike

我想使用 Interrupt() 方法中断线程,但是我遇到了无法解释的行为。

如代码所示,从MainActivity调用worker方法cancel()不能中断线程,而调用workerThread.interrupt()可以。

如果工作线程自己调用cancel(),它就会中断。

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

我认为这可能是一个安全异常,因为UIThread尝试中断workerThread,但它没有抛出。如果,调用workerThread.interrupt()时也应该抛出?


Worker.java

package com.example.threadapp;
public class Worker implements Runnable {

public void cancel() {
Log.d("Threading", "call Thread.currentThread().interrupt()");
try {
Thread.currentThread().interrupt();
} catch (SecurityException e) {
e.printStackTrace();
Log.d("Threading", "SecurityException while interrupting");
}

}

@Override
public void run() {
//
while(!Thread.currentThread().isInterrupted()) {
Log.d("Threading", "Worker alive");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
cancel();
}
//cancel(); //interrupts thread
//Thread.currentThread().interrupt(); //interrupts thread

}
//
Log.d("Threading", "Worker Thread closing");
}
}


MainActivity.java

public class MainActivity extends AppCompatActivity {

private Worker worker;
private Thread workerThread;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

worker = new Worker();
workerThread = new Thread(worker);
workerThread.start();

(new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
@Override
public void run() {
Log.d("Threading", " call worker.cancel()");
worker.cancel(); //doesn't interrupt thread
//workerThread.interrupt(); //interrupts thread
}
}, 10000);
}
}

最佳答案

worker.cancel 在主线程中被调用。因此,cancel方法中的Thread.currentThread()返回主线程,因此主线程调用了interrupt方法。在这种情况下,您不会中断工作线程。

关于java - 从方法中中断线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60429149/

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