今天对多线程进行探索:
使用步骤:
具体使用:
// 步骤1:创建线程类 (继承自Thread类) class MyThread extends Thread{ // 步骤2:复写run(),内容 = 定义线程行为 @Override public void run(){ ... // 定义的线程行为 } } // 步骤3:创建线程对象,即 实例化线程类 MyThread mt=new MyThread(“线程名称”); // 步骤4:通过 线程对象 控制线程的状态,如 运行、睡眠、挂起 / 停止 // 此处采用 start()开启线程 mt.start();
匿名类
// 步骤1:采用匿名类,直接 创建 线程类的实例 new Thread("线程名称") { // 步骤2:复写run(),内容 = 定义线程行为 @Override public void run() { // 步骤3:通过 线程对象 控制线程的状态,如 运行、睡眠、挂起 / 停止 }.start();
实例:(使用ListView显示Mysql中数据)
private void initListHis() { MyThread1 myThread1 = new MyThread1(); Thread thread = new Thread(myThread1); thread.start(); } private class MyThread1 implements Runnable { @Override public void run() { TextView textView = findViewById(R.id.his_tv_userName); String Names = textView.getText().toString(); try { mDataHis = Send_res.find_his(Names); } catch (Exception e) { throw new RuntimeException(e); } Message msg = new Message(); msg.what = 1; myHandler1.sendMessage(msg); } } private final Handler myHandler1 = new Handler(Looper.myLooper()) { @Override public void handleMessage(@NonNull Message msg) { if (msg.what == 1) { HisListAdapter hisListAdapter = new HisListAdapter(BuHisActivity.this, mDataHis); listView1 = findViewById(R.id.bu_his_list); listView1.setAdapter(hisListAdapter); } } };
标签:13,run,Thread,05,步骤,void,线程,2023,new From: https://www.cnblogs.com/JJTyyds/p/17397739.html