线程创建
- Thread:继承Thread类(重点)
- Runnable:实现Runnable接口(重点,推荐)
- Callable:实现Callable接口(了解)
实现Runnable接口
- 定义MyRunnable类实现Runable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
推荐使用Runnable接口,因为Java是单继承,但接口可以实现多个
线程开启不一定立即执行,需要看CPU的调度
public class StartRunnable implements Runnable{
@Override
public void run() {
// 线程体
for (int i = 0; i < 200; i++) {
System.out.println("Runnable接口实现多线程");
}
}
public static void main(String[] args) {
// 调用线程
StartRunnable startRunnable = new StartRunnable();
// 需要用Thread对象,只有在Thread中有start方法,代理
Thread thread = new Thread(startRunnable);
// 启动
thread.start();
for (int i = 0; i < 200; i++) {
System.out.println("顺序执行?");
}
}
}
Thread类也实现了Runnable接口,这俩实际都是是完成run()方法的重写。Runnable多了一步操作需要Thread做代理再调用start方法。
- 下载图片,实现Runnable接口
public class PicThread implements Runnable{
private String url = ""; // 网络图片地址
private String name = ""; // 保存路径
// 构造器,初始化地址
public PicThread(String url,String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("路径"+name);
}
// 启动线程
public static void main(String[] args) {
String url = "https://img0.bdstatic.com/static/searchdetail/img/logo-2X_2dd9a28.png";
String name = "C:\\Users\\Jie7\\IdeaProjects\\Test\\src\\baidulogo";
// 多线程,启动,无序
PicThread picThread1 = new PicThread(url, name +"1.png");
PicThread picThread2 = new PicThread(url, name +"2.png");
PicThread picThread3 = new PicThread(url, name +"3.png");
// Thread 代理,传入 Runnable对象
Thread t1 = new Thread(picThread1);
Thread t2 = new Thread(picThread2);
Thread t3 = new Thread(picThread3);
// 调用
t1.start();
t2.start();
t3.start();
}
}
class WebDownloader {
// 远程下载
// 远程路径,存储地址+名字
public void downloader(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件下载失败");
}
}
}