实现Java多线程

前两种最为常用

1.继承Thread类,重写run()方法

Thread本质上也是实现了Runnable接口的一个实例,它代表了一个线程的实例,启动线程的唯一方法是通过Thread类的start()方法。他是一个native本地方法,将启动一个新线程,并执行run()方法(Thread中提供的run()方法是一个空方法)。

调用start()方法后并不是立即执行多线程代码,而是使得该线程变为可运行态,时候时候运行多线程代码是由操作系统决定的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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()方法

  1. 自定义类并实现Runable接口,实现run方法
  2. 创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
  3. 调用Thread的start方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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(); //开启线程
}
}

3.实现Callable接口,重写call()方法

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器