重写run( ) 方法实现多线程的两种方法:
package com.jjw.jjwan.threadtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; //两种方法实现多线程 /* * 创建线程方法一步骤: * 1 定义一个类继承Thread。 * 2 重写run方法。 * 3 创建子类对象,就是创建线程对象。 * 4 调用start方法,开启线程并让线程执行,同时还会告诉jvm去调用run方法。 * */ /* * 创建线程方法二步骤: * 1、定义类实现Runnable接口 * 2、覆盖接口中的run方法 * 3、创建Thread类的对象 * 4、将Runnable接口的子类对象作为参数传递给Thread类的构造函数 * 5、调用Thread类的start方法开启线程 * */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ////////方法一调用 MyThread myThread = new MyThread(); myThread.start(); ///////方法二调用 MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } /* * 方法一 * */ public class MyThread extends Thread{ @Override public void run() { //把耗时的任务放入此方法中 } } /* * 方法二 * */ public class MyRunnable implements Runnable{ @Override public void run() { //写自己的耗时任务 } } }