Java共有三种方法来创建和启动线程:
一、继承Thread类:
1、创建线程并重写run()方法。
2、创建子类对象并通过start()方法启动线程。
二、实现Runnable接口:
1、创建线程并重写run()方法。
2、创建Thread对象,把实现了Runnable接口的对象作为参数传入,并通过Thread对象的start方法启动。
三、实现Callable接口,不作了解。
注意:
继承Thread类方式的多线程:
• 优势:编写简单。
• 劣势:无法继承其它父类。
实现Runnable接口方式的多线程:
• 优势:可以继承其它类,多线程可共享同一个Runnable对象,同一Runnable对象中的变量也是共用的。
• 劣势:内部无start()方法,需创建Thread对象。访问当前线程时需调用Thread.currentThread()方法。
Runnable接口方式要通用一些。
要点:
1、新建的线程不会自动开始运行,必须通过start( )方法启动。
2、start方法是Thread内的方法,不是Runnable接口的方法。
继承Thread:
class 继承Thread extends Thread {//继承Thread
@Override//重写run()
public void run() {//线程入口点,方法内是线程体
for(int i=0;i<20;i++) {
System.out.println("i'am Thread");
}
}
public static void main(String[] args) {
继承Thread st = new 继承Thread();//创建子类对象
st.start();//启动
for(int i=0;i<20;i++) {
System.out.println("i'm the main");
}
}
}
实现Runnable接口:
class 实现Runnable implements Runnable {//实现Runnable接口
@Override
public void run() {
for (int i=0;i<10;i++) {
System.out.println("i'm thread too");
}
}
public static void main(String[] args) {
//创建Thread对象,把实现了Runnable接口的对象作为参数传入;
Thread thread1 = new Thread(new 实现Runnable());
thread1.start();//启动线程;
Thread thread2 = new Thread(new 实现Runnable());
thread2.start();
}
}
实现Callable接口:
public class 实现Callable implements Callable<Boolean> {//实现Callable接口
private String srcName;
private String destName;
public 实现Callable(String srcName, String destName) {
this.srcName = srcName;
this.destName = destName;
}
public Boolean call() throws Exception {
FileUtils f = new FileUtils();
f.copy(srcName,destName);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
实现Callable c1 = new 实现Callable("aaa.txt","aa.txt");
实现Callable c2 = new 实现Callable("bbb.txt","bb.txt");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(2);
//提交执行:
Future<Boolean> result1 =ser.submit(c1);
Future<Boolean> result2 =ser.submit(c2);
//获取结果:
boolean r1 =result1.get();
boolean r2 =result2.get();
//关闭服务:
ser.shutdownNow();
}
}