版权声明:本文为博主原创文章,未经博主允许不得转载! https://blog.csdn.net/qq_25560423/article/details/73556144
前两种最为常用
1.继承Thread类,重写run()方法
Thread本质上也是实现了Runnable接口的一个实例,它代表了一个线程的实例,启动线程的唯一方法是通过Thread类的start()方法。他是一个native本地方法,将启动一个新线程,并执行run()方法(Thread中提供的run()方法是一个空方法)。
调用start()方法后并不是立即执行多线程代码,而是使得该线程变为可运行态,时候时候运行多线程代码是由操作系统决定的。
package test;
/**
* @Author ZhangQiong
* @Date 2017/6/19
* @Time 21:59.
*/
public class MyThread extends Thread{
public void run(){
System.out.println("Thread body"); //线程的函数体
}
}
class Test1{
public static void main(String[] args) {
MyThread thread =new MyThread();
thread.start(); //开启线程
}
}
2.实现Runnabl接口,并实现该接口的run()方法
- 自定义类并实现Runable接口,实现run方法
- 创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
- 调用Thread的start方法。
package test;
/**
* @Author ZhangQiong
* @Date 2017/6/19
* @Time 22:06.
*/
class MyThread implements Runnable {
@Override
public void run() {
System.out.println("thread body");
}
}
class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
Thread t =new Thread(thread);
t.start(); //开启线程
}
}