// 重写run()方法, alt+insert快捷键 public class StartThread1 extends Thread{ // 线程入口点 @Override public void run() { // 线程体 for (int i = 0; i < 20; i++) { System.out.println("多线程"); } } } // 调用start()方法启动线程 public class MainThread { public static void main(String[] args) { // 创建线程对象 StartThread1 th1 = new StartThread1(); th1.start(); // start 启用后和底下代码交替执行 for (int i = 0; i < 2000; i++) { System.out.println("main方法"); } } }
线程开启不一定立即执行,需要看CPU的调度
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; public class PicThread extends Thread { 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"); picThread1.start(); picThread2.start(); picThread3.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("文件下载失败"); } } }