-
1.继承Thread类,重写run()方法,调用start()开启线程
public class TestThread1 extends Thread{ @Override public void run() { //run方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我在听歌"+i); } } public static void main(String[] args) { //main是主线程 //线程开启不一定立即执行,由cpu调度执行 //创建线程,执行run方法 TestThread1 testThread1 = new TestThread1(); //调用start方法开启线程,与主线程同时(交替)执行 testThread1.start(); for (int i = 0; i < 1000; i++) { System.out.println("我在看书"+i); } } }
-
2.实现Runnable接口,重写run()方法
public class TestThread3 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接口实现类 TestThread3 testThread3 = new TestThread3(); //创建线程对象,通过线程对象来开启线程,代理模式 new Thread(testThread3).start(); for (int i = 0; i < 1000; i++) { System.out.println("我在看书"+i); } } }
推荐使用实现Runnable接口实现多线程,避免类单继承局限性,方便一个对象被多个线 程使用
-
3.实现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) { TestCallable t1 = new TestCallable("https://img-blog.csdnimg.cn/20210702210142375.png", "1.png"); TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/20210626223037856.png", "2.png"); TestCallable t3 = new TestCallable("https://img-blog.csdnimg.cn/20210626223211760.png", "3.png"); //1.创建执行服务 ExecutorService ser = Executors.newFixedThreadPool(3);//创建容纳3个线程的线程池 //2.提交执行 Future<Boolean> result1 = ser.submit(t1); Future<Boolean> result2 = ser.submit(t2); Future<Boolean> result3 = ser.submit(t3); //3.获取结果 try { Boolean r1 = result1.get(); Boolean r2 = result2.get(); Boolean r3 = result3.get(); System.out.println(r1+" "+r2+" "+r3); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } //关闭服务 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异常,downloder方法出现问题"); } } }