这里简述一下Java中实现多线程的三种方法:
一、继承Thread类
即继承Thread类后,自行完成run()方法,即可通过start()方法启动线程。
public class method1 extends Thread{
public void run(){
System.out.println("MyFirstWay!");
}
}
主函数如下:
public class test1 {
public static void main(String[] args) {
method1 meth1 = new method1();
method1 meth2 = new method1();
meth1.start();
meth2.start();
}
}
运行结果如下:
二、实现Runable()接口
即当所写的类已经继承一个接口时,使用Runnable()接口,实例化Thread,再把写的类传入,使用start()方法启动线程。
public class method2 implements Runnable{
@Override
public void run() {
System.out.println("MySecondMethod!");
}
}
主函数及运行结果如下:
public class test2 {
public static void main(String[] args) {
method2 method2 = new method2();
method2 method22 = new method2();
Thread thread1 = new Thread(method22);
Thread thread = new Thread(method2);
thread1.start();
thread.start();
}
}
三、实现Callable()接口
可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。
public class method3 implements Callable<String>{
@Override
public String call() throws Exception {
return "method3";
}
}
主函数及运行结果如下:
public class test3 {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<?> future = threadPool.submit(new method3());
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}