Java中创建线程有两种方式:继承Thread重写run()与实现Runnable()接口通过Thread构造。
继承Thread重写run()
创建一个TestThread继承自Thread,然后调用start()运行线程
TestThread testThread = new TestThread();
testThread.start();
public class TestThread extends Thread{
@Override
public void run() {
super.run();
Log.i("thread","TestThread");
}
}
打印的log为:TestThread
I/thread: TestThread
实现Runnable接口
定义一个类TestRunnable实现Runnable的run方法,通过Thread的构造函数传入一个TestRunnable对象,调用start()开启线程
Thread runnable = new Thread(new TestRunnable());
runnable.start();
public class TestRunnable implements Runnable{
@Override
public void run() {
Log.i("thread","testRunnable");
}
}
打印的log为:testRunnable
I/thread: testRunnable
继承Thread类与实现Runnable接口的原理和区别
通过上面的两种方式都可以实现多线程,那么将TestRunnable对象传给TestThread会是怎样的呢?代码走起