java多线程实现主要有三个方法:
1.继承Thread类实现多线程
2.Rannable接口实现多线程
3.Callable实现多线程
继承Thread类实现多线程
java.lang.Thread是线程操作的核心类,由JDK1.0提供,新建一个线程最简单的方法就是直接继承Thread类而后覆写类中的run()方法。
class MyThread extends Thread{
private String str;
public MyThread (String str) {
this.str = str;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(this.str+" i = "+i);
}
}
}
启动多线程的方式是调用Thread类中start()方法,而不是调用run()方法。
public synchronized void start()
这个方法会自动调用线程的run()方法,至于为什么要通过start()方法来调用run()方法,而不是直接调用run()方法,这个我们下次在深入讨论一下。
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程1");
MyThread mt2 = new MyThread("线程2");
MyThread mt3 = new MyThread("线程3");
mt1.start();
mt2.start();
mt3.start();
}
而且无论什么方式实现多线程,它的启动都是调用Thread类提供的start()方法。
Runnable接口实现多线程
Thread类的核心功能是进行线程的启动,但是为了实现多线程直接去继承Thread类就会有继承局限,而不能继承其他类。所以在java中提供另一种实现模式:继承Runnable接口。
class MyThread implements Runnable
此时MyThread类实现了Runnable接口,但是没有start()方法被继承了,所以就需要Thread类提供的构造方法
public Thread(Runnable target)
这个方法可以接收Runnable接口的对象,然后在调用start()方法。
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程1");
MyThread mt2 = new MyThread("线程2");
MyThread mt3 = new MyThread("线程3");
new Thread(mt1).start();
new Thread(mt2).start();
new Thread(mt3).start();
定义子类实现Runnable接口,通过Thread(Runnable target)构造实例化Thread对象,返回值为void。
使用Runnable接口实现的多线程类可以多继承,能更好的描述资源共享。
Callable接口实现多继承
这是JDK1.5以后追加的一种实现方式,也是唯一一个有返回值的线程实现方式,并且也可以多继承。
class MyThread implements Callable<V>
Callable中需要用到两个方法:
java.util.concurrent.Callable<V>:
V call() throws Exception:线程执行后有返回值V
java.util.Future<V>:
V get() throws InterruptedException , ExecutionException:取得Callable接口call方法的返回值。
这里们通过一个卖票来看一下
class MyThread implements Callable<String> {
private int ticket = 10;
@Override
public String call() throws Exception {
while(this.ticket > 0) {
System.out.println("剩余票数:"+this.ticket--);
}
return "票买完啦";
}
}
测试代码
FutureTask<String> task = new FutureTask<>(new MyThread());
new Thread(task).start();
new Thread(task).start();
System.out.println(task.get());
定义子类实现Callable接口,通过FutureTask和Thread(Runnable target)构造实例化Thread对象,FutureTask的get()方法获取返回的结果。
当线程需要返回值时只能采用Callable接口实现多线程。