安卓通过实现点击按钮实现线程停止与开启

xiaoxiao2021-02-28  100

public class MainActivity extends Activity implements android.view.View.OnClickListener { Button bt1, bt2; Thread thread; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt1 = (Button) findViewById(R.id.bt1); bt2 = (Button) findViewById(R.id.bt2); bt1.setOnClickListener(this); bt2.setOnClickListener(this); thread = new Thread(new Runnable() { public void run() { while (!thread.currentThread().interrupted()) { try { /** * To do someting */ thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); thread.interrupt(); //防止一些不重要的异常抛出 } } } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt1: thread.start(); //开始线程 break; case R.id.bt2: thread.interrupt();//关闭线程 break; default: break; } } }
转载请注明原文地址: https://www.6miu.com/read-47626.html

最新回复(0)