四、继承Thread类
步骤:
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
//方式一:继承Thread类 public class Demo01 extends Thread{ //主线程 public static void main(String[] args) { Demo01 demo01 = new Demo01(); demo01.start(); for (int i = 0; i < 200; i++) { System.out.println("我是主线程:"+i); } } @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("我是子线程:"+i); } } }
部分结果:可以看出来,两条线程交替执行。
练习:多线程同步下载网络图片
public class MyThread extends Thread{ private String url; private String name; public MyThread(String url, String name) { this.url = url; this.name = name; } @Override public void run() { WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(this.url,this.name); } public static void main(String[] args) { MyThread t1 = new MyThread("https://yjsc.gxu.edu.cn/images/2021-for100.jpg","1.jpg"); MyThread t2 = new MyThread("https://yjsc.gxu.edu.cn/images/2022yjsy.jpg","2.jpg"); MyThread t3 = new MyThread("https://yjsc.gxu.edu.cn/images/2022newyear.jpg","3.jpg"); MyThread t4 = new MyThread("https://yjsc.gxu.edu.cn/images/202010banner.jpg","4.jpg"); t1.start(); t2.start(); t3.start(); t4.start(); } } class WebDownloader{ public void downloader(String url, String name) { try { FileUtils.copyURLToFile(new URL(url),new File(name)); System.out.println("图片:"+name+",下载完成"); } catch (IOException e) { throw new RuntimeException(e); } } }
结果: