JAVA多线程
2021/5/22 20:29:41
本文主要是介绍JAVA多线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1. 进程,线程
一个进程有多个线程,如视频同时听声音,看图像,看弹幕等
程序与线程----
多线程----
2. 线程创建
- 继承Thread类(重点)
- 实现Runnable接口(重点)
- 实现Callable接口(了解)
2.1 继承Thread类
三个步骤:
- 继承Thread类
- 重写run()方法
- 调用start()方法开启线程
注意:线程开启不一定立即执行,由CPU调度
//创建线程方式一:继承Thread类,重写run()方法,调用start()开启线程 public class TestThread1 extends Thread { public static void main(String[] args) { //main线程,主线程 //创建线程对象 TestThread1 thread1 = new TestThread1(); thread1.start();//调用start()方法 for (int i = 0; i < 200; i++) { System.out.println("我在看代码---" + i); } } @Override public void run() { //run()方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我在学习多线程---" + i); } } }
2.1.1 练习Thread,多线程同步下载图片
//练习Thread,多线程同步下载图片 public class TestThresd2 extends Thread{ private String url; //保存图片地址 private String name; //保存的文件名 public TestThresd2(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) { TestThresd2 t1 = new TestThresd2("https://www.runoob.com/wp-content/uploads/2015/03/Git-push-command.jpeg","1.jpeg"); TestThresd2 t2 = new TestThresd2("https://www.runoob.com/wp-content/uploads/2015/03/github1.jpg","2.jpg"); TestThresd2 t3 = new TestThresd2("https://www.runoob.com/wp-content/uploads/2015/03/79A84530-7DC0-4D25-9F83-8776433A4C32.jpg","3.jpg"); 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方法出现问题"); } } }
2.2 实现Runnable接口(推荐使用)
三个步骤:
- 实现Runnable接口
- 重写run()方法
- 执行线程需要丢入runnable接口实现类,调用start()方法
//创建线程方法二 //实现Runnable接口,重写run()方法,执行线程需要丢入runnable接口实现类,调用start()方法 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 t = new TestThread3(); //创建线程对象,通过线程对象开启线程代理 Thread thread = new Thread(t); thread.start(); for (int i = 0; i < 200; i++) { System.out.println("我在看代码---" + i); } } }
两种方法对此
2.2.1 多线程买火车票的例子
发现问题:多个线程操作同一个资源的情况下,线程不安全,并发问题
public class TestThread4 implements Runnable{ //票数 private int ticketNums = 10; @Override public void run() { while (true) { if (ticketNums <= 0) break; //模拟延时 try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"票"); } } public static void main(String[] args) { TestThread4 ticket = new TestThread4(); new Thread(ticket,"小明").start(); new Thread(ticket,"老师").start(); new Thread(ticket,"小黄").start(); } }
2.2.2 龟兔赛跑
public class Race implements Runnable{ private static String winner; @Override public void run() { for (int i = 0; i <= 100; i++) { //模拟兔子休息 if (Thread.currentThread().getName().equals("兔子") && i % 10 ==0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } //判断比赛是否结束 boolean flag = gameOver(i); if (flag) break; System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步"); } } //判断比赛是否结束 private boolean gameOver(int steps) { //判断是否有胜利者 if (winner != null) return true; else { if (steps >= 100) { winner = Thread.currentThread().getName(); System.out.println("Winner is " + winner); return true; } } return false; } public static void main(String[] args) { Race race = new Race(); new Thread(race,"兔子").start(); new Thread(race,"乌龟").start(); } }
2.3 实现Callable接口
案列:多线程下载图片
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("https://www.runoob.com/wp-content/uploads/2015/03/Git-push-command.jpeg","1.jpeg"); TestCallable t2 = new TestCallable("https://www.runoob.com/wp-content/uploads/2015/03/github1.jpg","2.jpg"); TestCallable t3 = new TestCallable("https://www.runoob.com/wp-content/uploads/2015/03/79A84530-7DC0-4D25-9F83-8776433A4C32.jpg","3.jpg"); //1. 创建执行服务 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方法出现问题"); } } }
Callable的好处:可以定义返回值;可以抛出异常
3. 静态代理
是线程的底层实现原理
静态代理模式总结
- 真实对象和代理对象都要实现同一个接口
- 代理对象要代理真实角色
好处:
代理对象可以做很多真实对象做不了的事情,真实对象专注做自己的事情
public class StaticProxy { public static void main(String[] args) { You you = new You(); WeddingCompany company = new WeddingCompany(you); company.HappyMarry(); } } //结婚接口 interface Marry{ void HappyMarry(); } //真实角色 class You implements Marry{ @Override public void HappyMarry() { System.out.println("我要结婚啦"); } } //代理角色,帮助你结婚 class WeddingCompany implements Marry{ //代理谁-->真实对象 private Marry target; public WeddingCompany(Marry target) { this.target = target; } @Override public void HappyMarry() { before(); this.target.HappyMarry();//真实对象 after(); } private void after() { System.out.println("结婚之后,收尾款"); } private void before() { System.out.println("结婚之前,布置现场"); } }
4. Lamda表达式(前提是函数式接口)
new Thread(()->System.out.println("i like thread")).start();
//推导lambda表达式 public class TestLambda { //3. 静态内部类 static class Like2 implements ILike{ @Override public void lambda() { System.out.println("i like lambda2"); } } public static void main(String[] args) { ILike like = new Like(); like.lambda(); like = new Like2(); like.lambda(); // 4. 局部内部类 class Like3 implements ILike{ @Override public void lambda() { System.out.println("i like lambda3"); } } like = new Like3(); like.lambda(); //5.匿名内部类,没有类的名称,必须借助接口或父类 like = new ILike() { @Override public void lambda() { System.out.println("i like lambda4"); } }; like.lambda(); //6. lambda简化 like = ()-> { System.out.println("i like lambda5");}; like.lambda(); } } //1. 定义一个函数式接口 interface ILike{ void lambda(); } //2. 实现类 class Like implements ILike{ @Override public void lambda() { System.out.println("i like lambda1"); } }
这篇关于JAVA多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程
- 2024-11-26Springboot单体架构搭建资料详解与实战教程
- 2024-11-26Springboot框架资料:新手入门教程
- 2024-11-26Springboot企业级开发资料入门教程
- 2024-11-26SpringBoot企业级开发资料详解与实战教程
- 2024-11-26Springboot微服务资料:新手入门全攻略