创建线程的三种方式
1、继承Thread类,重写run方法,调用start方法启动线程;
package Thread; //创建线程方式一:继承Thread类,重写run()方法,调用start开启线程 //总结:注意,线程开启不一定立即执行,由CPU调度执行 public class threadDemo1 extends Thread { @Override public void run() { //run方法线程体 for (int i = 0; i < 5; i++) { System.out.println("我在看代码---"+i); } } public static void main(String[] args) { //main线程,主线程 //创建一个线程对象 threadDemo1 threadDemo1 = new threadDemo1(); //调用start()方法开启线程 threadDemo1.start(); for (int i = 0; i < 1000; i++) { System.out.println("我在学习"+i); } } }
结果:
2、实现Runnable方法,重写run方法,执行线程需要丢入runable接口实现类,启动调用start方法;
package Thread; //创建线程方法2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法 public class threadDemo3 implements Runnable { @Override public void run() { //run方法线程体 for (int i = 0; i < 5; i++) { System.out.println("我在看代码---"+i); } } public static void main(String[] args) { //创建runnable接口的实现类对象 threadDemo3 threadDemo3 = new threadDemo3(); //调用start()方法开启线程 Thread thread = new Thread(threadDemo3); thread.start(); for (int i = 0; i < 1000; i++) { System.out.println("我在学习"+i); } } }
3、实现Callable接口;
package Thread; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.*; //线程创建方式三:实现Callable接口 /** * callable的好处: * 1、可以定义返回值 * 2、可以抛出异常 */ public class TestCallable implements Callable<Boolean> { private String url;//网络图片地址 private String name;//保存的文件名 public TestCallable(String url,String name){ this.url = url; this.name = name; } @Override public Boolean call() { WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(url,name); System.out.println("下载了文件名为:"+name+"的文件"); return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { TestCallable t1 = new TestCallable("http://img.tuguaishou.com/ips_templ_preview/w432_q100/c5/f6/a7/lg_2559370_1572354908_5db83b5c038ec.jpg?auth_key=2239632000-0-0-6c120c2d0677dc637cb897b4e030d240", "1.jpg"); TestCallable t2 = new TestCallable("http://img.tuguaishou.com/ips_templ_preview/w432_q100/f9/15/19/lg_3402655_1603039421_5f8c70bd859a6.jpg?auth_key=2239632000-0-0-12b2428b47e0b0163ba832a29b2a3951", "2.jpg"); TestCallable t3 = new TestCallable("http://img.tuguaishou.com/ips_templ_preview/w432_q100/c5/f6/a7/lg_2559370_1572354908_5db83b5c038ec.jpg?auth_key=2239632000-0-0-6c120c2d0677dc637cb897b4e030d240", "3.jpg"); //1、创建执行服务 3个 ExecutorService ser = Executors.newFixedThreadPool(3); //2、提交执行 Future<Boolean> r1 = ser.submit(t1); Future<Boolean> r2 = ser.submit(t2); Future<Boolean> r3 = ser.submit(t3); //3、获取结果 boolean rs1 = r1.get(); boolean rs2 = r2.get(); boolean rs3 = r3.get(); //4、关闭服务 ser.shutdownNow(); } } //下载器 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方法出现问题!"); } } }