我正在学习 Android 中的线程和并发。我正在创建一个基本程序,其中主线程向工作线程发送中断以停止工作线程的处理。主线程在 5 秒后发送中断。我有 2 个线程:一个主线程和一个工作线程。
代码:
package com.example.testthread;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new thread and start it
NewThread newThread = new NewThread();
newThread.start();
// Get the Looper of the new thread and create a Handler associated with it
Looper looper = newThread.getLooper();
mHandler = new Handler(looper);
// Post a Runnable to the new thread's Handler after a delay of 5 seconds
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
newThread.interrupt();
}
}, 5000);
}
private static class NewThread extends Thread {
private boolean isRunning = true;
@Override
public void run() {
Looper.prepare();
while (isRunning) {
Log.d("NewThread", "Thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d("NewThread", "Thread was interrupted");
isRunning = false;
}
}
Looper.loop();
}
}
}
无法解决问题。帮助将不胜感激!
我认为 Thread 类中没有称为
getLooper()
的方法,它仅在 Handler 类中可用,但是您可以通过在 NewThread 类中创建一个函数来切换回isRunning to false,但你需要做到这一点volatile
!