第一种:继承Thread(不推荐)
public class DownloadMusic extends Thread {
@Override
public void run() {
int count = 0;
while(true){
count++;
if (count==100){
break;
}
}
}
}
开启线程方式:
public void testThread(){
DownloadMusic downloadMusic = new DownloadMusic(1);
downloadMusic.start();
}
第二种:实现Runnable(推荐)
public class DownLoadBook implements Runnable {
@Override
public void run() {
for (int i=0; i<100; i++){
System.out.println(Thread.currentThread().getName()+" 下载书记 "+ i);
}
}
}
开启线程方式:
public void testRunnable(){
Thread bookThread1 = new Thread(new DownLoadBook(), "bookThread01");
Thread bookThread2 = new Thread(new DownLoadBook(), "bookThread02");
bookThread1.start();
bookThread2.start();
}
第三种:实现Callable(推荐)
public class DownLoadImage implements Callable<String> {
@Override
public String call() throws Exception {
for(int i=0; i<100; i++){
System.out.println(Thread.currentThread().getName()+" 下载图片 " + i);
}
return Thread.currentThread().getName()+" 下载成功";
}
}
开启线程方式:
public void testCallable() throws ExecutionException, InterruptedException {
FutureTask<String> taskA = new FutureTask<>(new DownLoadImage()); //创建任务A
FutureTask<String> taskB = new FutureTask<>(new DownLoadImage()); //创建任务B
Thread image001 = new Thread(taskA, "image001"); //创建任务A对应的线程
Thread image002 = new Thread(taskB, "image002"); //创建任务B对应的线程
image001.start();
image002.start();
System.out.println(taskA.get()); //获取任务A的返回值
System.out.println(taskB.get()); //获取任务B的返回值
}
总结:
继承Thread的方式不利于继承类的扩展,因为继承类只能有一个父类(单继承);
如果线程不需要返回数据,推荐使用 实现Runnable的方式;
如果线程需要返回数据,推荐使用 实现Callable的方式;