学习文档:https://www.cnblogs.com/gh110/p/15153666.html
学习视频:https://www.bilibili.com/video/BV1V4411p7EF/
1.线程创建(三种方法)
1.1继承Thread类(重要)
a. 自定义线程类继承Thread
类
b. 重写run()
方法,编写线程执行体
c. 创建线程对象,调用start()
方法启动线程
测试
// 创建线程方式一:继承Thread类,重写run()方法,调用start开启线程 //总结:注意,线程开启不一定立即执行,由CPU调度执行 public class TestThread1 extends Thread{ // run()方法线程体 @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("我在阅读代码-----" + i); } } // main线程 public static void main(String[] args) { // 创建一个线程对象 TestThread1 thread = new TestThread1(); // 调用start()开启线程 thread.start(); for (int i = 0; i < 200; i++) { System.out.println("多线程学习中……" + i); } } }
多线程网图下载:
1.下载commons-io.jar包:https://commons.apache.org/proper/commons-io/download_io.cgi
下载好后将压缩包解压,复制.jar文件到项目新建的lib文件下 --->右键lib文件选择“Add as Library”
测试
package com.xinyu.demo01; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; /** * @author subeiLY * @create 2021-06-07 08:41 */ // 练习Thread,实现多线程同步下载图片 public class TestThread02 extends Thread{ private String url; private String name; // 有参构造 public TestThread02(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) { TestThread02 t1 = new TestThread02("http://browser9.qhimg.com/bdm/768_474_0/t010824ab8b5cdfa138.jpg","str1.png"); TestThread02 t2 = new TestThread02("http://browser9.qhimg.com/bdm/768_474_0/t012468d019e3ce466b.jpg","str2.png"); TestThread02 t3 = new TestThread02("http://browser9.qhimg.com/bdm/384_237_0/t01039b44f7c7ca5ca3.jpg","str3.png"); 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("IO异常,downloader下载方法异常"); } } }
1.2 实现Runnable接口
- 推荐使用Runnable对象,因为Java单继承的局限性;
- 自定义线程类实现
Runnable
接口; - 实现
run()
方法,编写线程执行体; - 创建线程对象,调用
start()
方法启动对象。
// 练习Thread,实现多线程同步下载图片 public class TestThread03 implements Runnable{ @Override public void run() { // run方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我在看代码-----" + i); } } public static void main(String[] args) { // 创建runnable接口的实现类对象 TestThread03 thread03 = new TestThread03(); // 创建线程对象,通过线程对象来开启我们的线程,代理 Thread thread = new Thread(thread03); // 调用start()开启线程 thread.start(); for (int i = 0; i < 200; i++) { System.out.println("我在学习多线程……" + i); } } }
标签:String,Thread,start,线程,new,多线程,public From: https://www.cnblogs.com/xinyu-yudian/p/16837502.html