实现java多线程有三种方法,继承Thread类,实现Runnable接口,使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。
1,通过继承Thread类,其本质还是实现了Runnable接口的一个实例,启动线程的唯一方法start()方法来启动一个新的线程,并复写父类的run()方法,例如
public class MyThread extends Thread{
public void run(){
System.out.println("this is thread");
}
}
在合适的地地方启动线程
MyThread mythread1= new MyThread();
mythread1.start();
MyThread mythread2=new MyThread();
mythread2.start();
2,通过实现Runnable接口,
如果一个类已经继承了另外一个类,就不能继承Thread类实现多线程了(java不支持多继承),这样就只能通过实现Runnable接口来实现多线程。例如
public class MyThread extends otherclass implements
Runnable{
public void run(){
System.out.println("this is thread");
}
}