使用布尔变量exit 来控制(变量在run方法内部)
public class MainActivity extends AppCompatActivity {
private Button searchGoBtn;
public volatile boolean exit = false;
public void go(View view){
exit=true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchGoBtn = (Button) findViewById(R.id.search_go_btn);
new Thread(){
@Override
public void run() {
while (!exit){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("FileDemo.run");
}
}
}.start();
}
}
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
比较正宗的写法(线程是内部类的形式)
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
MyThread myThread;
public void go(View view){
myThread.exit=true;
}
class MyThread extends Thread{
public volatile boolean exit = false;
@Override
public void run() {
while (!exit){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("FileDemo.run");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myThread = new MyThread();
myThread.start();
}
}