1、多线程(多线程的引入)

  • 1.什么是线程

    • 线程是程序执行的一条路径, 一个进程中可以包含多条线程
    • 多线程并发执行可以提高程序的效率, 可以同时完成多项工作
  • 2.多线程的应用场景
    • 红蜘蛛同时共享屏幕给多个电脑
    • 迅雷开启多条线程一起下载
    • QQ同时和多个人一起视频
    • 服务器同时处理多个客户端请求

2、多线程(多线程并行和并发的区别)

  • 并行就是两个任务同时运行,就是甲任务进行的同时,乙任务也在进行。(需要多核CPU)
  • 并发是指两个任务都请求运行,而处理器只能按受一个任务,就把这两个任务安排轮流进行,由于时间间隔较短,使人感觉两个任务都在运行。
  • 比如我跟两个网友聊天,左手操作一个电脑跟甲聊,同时右手用另一台电脑跟乙聊天,这就叫并行。
  • 如果用一台电脑我先给甲发个消息,然后立刻再给乙发消息,然后再跟甲聊,再跟乙聊。这就叫并发。

3、多线程(Java程序运行原理和JVM的启动是多线程的吗)

  • A:Java程序运行原理

    • Java命令会启动java虚拟机,启动JVM,等于启动了一个应用程序,也就是启动了一个进程。该进程会自动启动一个 “主线程” ,然后主线程去调用某个类的 main 方法。
  • B:JVM的启动是多线程的吗

    • JVM启动至少启动了垃圾回收线程和主线程,所以是多线程的。

4、多线程(多线程程序实现的方式1)

  • 1.继承Thread

    • 定义类继承Thread
    • 重写run方法
    • 把新线程要做的事写在run方法中
    • 创建线程对象
    • 开启新线程, 内部会自动执行run方法
      1. public class Demo2_Thread {
      2. /**
      3. * @param args
      4. */
      5. public static void main(String[] args) {
      6. MyThread mt = new MyThread(); //4,创建自定义类的对象
      7. mt.start(); //5,开启线程
      8. for(int i = 0; i < 3000; i++) {
      9. System.out.println("bb");
      10. }
      11. }
      12. }
      13. class MyThread extends Thread { //1,定义类继承Thread
      14. public void run() { //2,重写run方法
      15. for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中
      16. System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
      17. }
      18. }
      19. }

5、多线程(多线程程序实现的方式2)

  • 2.实现Runnable

    • 定义类实现Runnable接口
    • 实现run方法
    • 把新线程要做的事写在run方法中
    • 创建自定义的Runnable的子类对象
    • 创建Thread对象, 传入Runnable
    • 调用start()开启新线程, 内部会自动调用Runnable的run()方法

      1. public class Demo3_Runnable {
      2. /**
      3. * @param args
      4. */
      5. public static void main(String[] args) {
      6. MyRunnable mr = new MyRunnable(); //4,创建自定义类对象
      7. //Runnable target = new MyRunnable();
      8. Thread t = new Thread(mr); //5,将其当作参数传递给Thread的构造函数
      9. t.start(); //6,开启线程
      10. for(int i = 0; i < 3000; i++) {
      11. System.out.println("bb");
      12. }
      13. }
      14. }
      15. class MyRunnable implements Runnable { //1,自定义类实现Runnable接口
      16. @Override
      17. public void run() { //2,重写run方法
      18. for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中
      19. System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
      20. }
      21. }
      22. }

6、多线程(实现Runnable的原理)

  • 查看源码

    • 1,看Thread类的构造函数,传递了Runnable接口的引用
    • 2,通过init()方法找到传递的target给成员变量的target赋值
    • 3,查看run方法,发现run方法中有判断,如果target不为null就会调用Runnable接口子类对象的run方法

7、多线程(两种方式的区别)

  • 查看源码的区别:

    • a.继承Thread : 由于子类重写了Thread类的run(), 当调用start()时, 直接找子类的run()方法
    • b.实现Runnable : 构造函数中传入了Runnable的引用, 成员变量记住了它, start()调用run()方法时内部判断成员变量Runnable的引用是否为空, 不为空编译时看的是Runnable的run(),运行时执行的是子类的run()方法
  • 继承Thread

    • 好处是:可以直接使用Thread类中的方法,代码简单
    • 弊端是:如果已经有了父类,就不能用这种方法
  • 实现Runnable接口
    • 好处是:即使自己定义的线程类有了父类也没关系,因为有了父类也可以实现接口,而且接口是可以多实现的
    • 弊端是:不能直接使用Thread中的方法需要先获取到线程对象后,才能得到Thread的方法,代码复杂

8、多线程(匿名内部类实现线程的两种方式)

  • 继承Thread类

    1. new Thread() { //1,new 类(){}继承这个类
    2. public void run() { //2,重写run方法
    3. for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中
    4. System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    5. }
    6. }
    7. }.start();
  • 实现Runnable接口

    1. new Thread(new Runnable(){ //1,new 接口(){}实现这个接口
    2. public void run() { //2,重写run方法
    3. for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中
    4. System.out.println("bb");
    5. }
    6. }
    7. }).start();

9、多线程(获取名字和设置名字)

  • 1.获取名字

    • 通过getName()方法获取线程对象的名字
  • 2.设置名字

    • 通过构造函数可以传入String类型的名字
      1. new Thread("xxx") {
      2. public void run() {
      3. for(int i = 0; i < 1000; i++) {
      4. System.out.println(this.getName() + "....aaaaaaaaaaaaaaaaaaaaaaa");
      5. }
      6. }
      7. }.start();
      8. new Thread("yyy") {
      9. public void run() {
      10. for(int i = 0; i < 1000; i++) {
      11. System.out.println(this.getName() + "....bb");
      12. }
      13. }
      14. }.start();
    • 通过setName(String)方法可以设置线程对象的名字
      1. Thread t1 = new Thread() {
      2. public void run() {
      3. for(int i = 0; i < 1000; i++) {
      4. System.out.println(this.getName() + "....aaaaaaaaaaaaaaaaaaaaaaa");
      5. }
      6. }
      7. };
      8. Thread t2 = new Thread() {
      9. public void run() {
      10. for(int i = 0; i < 1000; i++) {
      11. System.out.println(this.getName() + "....bb");
      12. }
      13. }
      14. };
      15. t1.setName("芙蓉姐姐");
      16. t2.setName("凤姐");
      17. t1.start();
      18. t2.start();

10、多线程(获取当前线程的对象)

  • Thread.currentThread(), 主线程也可以获取

      1. new Thread(new Runnable() {
      2. public void run() {
      3. for(int i = 0; i < 1000; i++) {
      4. System.out.println(Thread.currentThread().getName() + "...aaaaaaaaaaaaaaaaaaaaa");
      5. }
      6. }
      7. }).start();
      8. new Thread(new Runnable() {
      9. public void run() {
      10. for(int i = 0; i < 1000; i++) {
      11. System.out.println(Thread.currentThread().getName() + "...bb");
      12. }
      13. }
      14. }).start();
      15. Thread.currentThread().setName("我是主线程"); //获取主函数线程的引用,并改名字
      16. System.out.println(Thread.currentThread().getName()); //获取主函数线程的引用,并获取名字

11、多线程(休眠线程)

  • Thread.sleep(毫秒,纳秒), 控制当前线程休眠若干毫秒1秒= 1000毫秒 1秒 = 1000 * 1000 * 1000纳秒 1000000000

    1. new Thread() {
    2. public void run() {
    3. for(int i = 0; i < 10; i++) {
    4. System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
    5. try {
    6. Thread.sleep(10);
    7. } catch (InterruptedException e) {
    8. e.printStackTrace();
    9. }
    10. }
    11. }
    12. }.start();
    13. new Thread() {
    14. public void run() {
    15. for(int i = 0; i < 10; i++) {
    16. System.out.println(getName() + "...bb");
    17. try {
    18. Thread.sleep(10);
    19. } catch (InterruptedException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    24. }.start();

12、多线程(守护线程)

  • setDaemon(), 设置一个线程为守护线程, 该线程不会单独执行, 当其他非守护线程都执行结束后, 自动退出

      1. Thread t1 = new Thread() {
      2. public void run() {
      3. for(int i = 0; i < 50; i++) {
      4. System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
      5. try {
      6. Thread.sleep(10);
      7. } catch (InterruptedException e) {
      8. e.printStackTrace();
      9. }
      10. }
      11. }
      12. };
      13. Thread t2 = new Thread() {
      14. public void run() {
      15. for(int i = 0; i < 5; i++) {
      16. System.out.println(getName() + "...bb");
      17. try {
      18. Thread.sleep(10);
      19. } catch (InterruptedException e) {
      20. e.printStackTrace();
      21. }
      22. }
      23. }
      24. };
      25. t1.setDaemon(true); //将t1设置为守护线程
      26. t1.start();
      27. t2.start();

13、多线程(加入线程)

  • join(), 当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续
  • join(int), 可以等待指定的毫秒之后继续

      1. final Thread t1 = new Thread() {
      2. public void run() {
      3. for(int i = 0; i < 50; i++) {
      4. System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
      5. try {
      6. Thread.sleep(10);
      7. } catch (InterruptedException e) {
      8. e.printStackTrace();
      9. }
      10. }
      11. }
      12. };
      13. Thread t2 = new Thread() {
      14. public void run() {
      15. for(int i = 0; i < 50; i++) {
      16. if(i == 2) {
      17. try {
      18. //t1.join(); //插队,加入
      19. t1.join(30); //加入,有固定的时间,过了固定时间,继续交替执行
      20. Thread.sleep(10);
      21. } catch (InterruptedException e) {
      22. e.printStackTrace();
      23. }
      24. }
      25. System.out.println(getName() + "...bb");
      26. }
      27. }
      28. };
      29. t1.start();
      30. t2.start();

14、多线程(礼让线程)

  • yield让出cpu

15、多线程(设置线程的优先级)

  • setPriority()设置线程的优先级

16、多线程(同步代码块)

  • 1.什么情况下需要同步

    • 当多线程并发, 有多段代码同时执行时, 我们希望某一段代码执行的过程中CPU不要切换到其他线程工作. 这时就需要同步.
    • 如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码.
  • 2.同步代码块

    • 使用synchronized关键字加上一个锁对象来定义一段代码, 这就叫同步代码块
    • 多个同步代码块如果使用相同的锁对象, 那么他们就是同步的

      1. class Printer {
      2. Demo d = new Demo();
      3. public static void print1() {
      4. synchronized(d){ //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象
      5. System.out.print("黑");
      6. System.out.print("马");
      7. System.out.print("程");
      8. System.out.print("序");
      9. System.out.print("员");
      10. System.out.print("\r\n");
      11. }
      12. }
      13. public static void print2() {
      14. synchronized(d){
      15. System.out.print("传");
      16. System.out.print("智");
      17. System.out.print("播");
      18. System.out.print("客");
      19. System.out.print("\r\n");
      20. }
      21. }
      22. }

17、多线程(同步方法)

  • 使用synchronized关键字修饰一个方法, 该方法中所有的代码都是同步的

    1. class Printer {
    2. public static void print1() {
    3. synchronized(Printer.class){ //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象
    4. System.out.print("黑");
    5. System.out.print("马");
    6. System.out.print("程");
    7. System.out.print("序");
    8. System.out.print("员");
    9. System.out.print("\r\n");
    10. }
    11. }
    12. /*
    13. * 非静态同步函数的锁是:this
    14. * 静态的同步函数的锁是:字节码对象
    15. */
    16. public static synchronized void print2() {
    17. System.out.print("传");
    18. System.out.print("智");
    19. System.out.print("播");
    20. System.out.print("客");
    21. System.out.print("\r\n");
    22. }
    23. }

18、多线程(线程安全问题)

  • 多线程并发操作同一数据时, 就有可能出现线程安全问题
  • 使用同步技术可以解决这种问题, 把操作数据的代码进行同步, 不要多个线程一起操作

    1. public class Demo2_Synchronized {
    2. /**
    3. * @param args
    4. * 需求:铁路售票,一共100张,通过四个窗口卖完.
    5. */
    6. public static void main(String[] args) {
    7. TicketsSeller t1 = new TicketsSeller();
    8. TicketsSeller t2 = new TicketsSeller();
    9. TicketsSeller t3 = new TicketsSeller();
    10. TicketsSeller t4 = new TicketsSeller();
    11. t1.setName("窗口1");
    12. t2.setName("窗口2");
    13. t3.setName("窗口3");
    14. t4.setName("窗口4");
    15. t1.start();
    16. t2.start();
    17. t3.start();
    18. t4.start();
    19. }
    20. }
    21. class TicketsSeller extends Thread {
    22. private static int tickets = 100;
    23. static Object obj = new Object();
    24. public TicketsSeller() {
    25. super();
    26. }
    27. public TicketsSeller(String name) {
    28. super(name);
    29. }
    30. public void run() {
    31. while(true) {
    32. synchronized(obj) {
    33. if(tickets <= 0)
    34. break;
    35. try {
    36. Thread.sleep(10);//线程1睡,线程2睡,线程3睡,线程4睡
    37. } catch (InterruptedException e) {
    38. e.printStackTrace();
    39. }
    40. System.out.println(getName() + "...这是第" + tickets-- + "号票");
    41. }
    42. }
    43. }
    44. }

19、多线程(火车站卖票的例子用实现Runnable接口)

20、多线程(死锁)

  • 多线程同步的时候, 如果同步代码嵌套, 使用相同锁, 就有可能出现死锁

    • 尽量不要嵌套使用

      1. private static String s1 = "筷子左";
      2. private static String s2 = "筷子右";
      3. public static void main(String[] args) {
      4. new Thread() {
      5. public void run() {
      6. while(true) {
      7. synchronized(s1) {
      8. System.out.println(getName() + "...拿到" + s1 + "等待" + s2);
      9. synchronized(s2) {
      10. System.out.println(getName() + "...拿到" + s2 + "开吃");
      11. }
      12. }
      13. }
      14. }
      15. }.start();
      16. new Thread() {
      17. public void run() {
      18. while(true) {
      19. synchronized(s2) {
      20. System.out.println(getName() + "...拿到" + s2 + "等待" + s1);
      21. synchronized(s1) {
      22. System.out.println(getName() + "...拿到" + s1 + "开吃");
      23. }
      24. }
      25. }
      26. }
      27. }.start();
      28. }

21、多线程(以前的线程安全的类回顾)

  • A:回顾以前说过的线程安全问题

    • 看源码:Vector,StringBuffer,Hashtable,Collections.synchroinzed(xxx)
    • Vector是线程安全的,ArrayList是线程不安全的
    • StringBuffer是线程安全的,StringBuilder是线程不安全的
    • Hashtable是线程安全的,HashMap是线程不安全的

JavaEE基础(二十四)/多线程的更多相关文章

  1. Bootstrap<基础二十四> 缩略图

    Bootstrap 缩略图.大多数站点都需要在网格中布局图像.视频.文本等.Bootstrap 通过缩略图为此提供了一种简便的方式.使用 Bootstrap 创建缩略图的步骤如下: 在图像周围添加带有 ...

  2. JavaEE基础(十四) /正则

    1.常见对象(正则表达式的概述和简单使用) A:正则表达式 是指一个用来描述或者匹配一系列符合某个语法规则的字符串的单个字符串.其实就是一种规则.有自己特殊的应用. 作用:比如注册邮箱,邮箱有用户名和 ...

  3. Bootstrap <基础二十九>面板(Panels)

    Bootstrap 面板(Panels).面板组件用于把 DOM 组件插入到一个盒子中.创建一个基本的面板,只需要向 <div> 元素添加 class .panel 和 class .pa ...

  4. Bootstrap <基础二十八>列表组

    列表组.列表组件用于以列表形式呈现复杂的和自定义的内容.创建一个基本的列表组的步骤如下: 向元素 <ul> 添加 class .list-group. 向 <li> 添加 cl ...

  5. Bootstrap <基础二十六>进度条

    Bootstrap 进度条.在本教程中,你将看到如何使用 Bootstrap 创建加载.重定向或动作状态的进度条. Bootstrap 进度条使用 CSS3 过渡和动画来获得该效果.Internet ...

  6. Bootstrap <基础二十五>警告(Alerts)

    警告(Alerts)以及 Bootstrap 所提供的用于警告的 class.警告(Alerts)向用户提供了一种定义消息样式的方式.它们为典型的用户操作提供了上下文信息反馈. 您可以为警告框添加一个 ...

  7. Bootstrap <基础二十二>超大屏幕(Jumbotron)

    Bootstrap 支持的另一个特性,超大屏幕(Jumbotron).顾名思义该组件可以增加标题的大小,并为登陆页面内容添加更多的外边距(margin).使用超大屏幕(Jumbotron)的步骤如下: ...

  8. Bootstrap<基础二十> 标签

    Bootstrap 标签.标签可用于计数.提示或页面上其他的标记显示.使用 class .label 来显示标签,如下面的实例所示: <!DOCTYPE html> <html> ...

  9. 二十四. Python基础(24)--封装

    二十四. Python基础(24)--封装 ● 知识结构   ● 类属性和__slots__属性 class Student(object):     grade = 3 # 也可以写在__slots ...

  10. Java15-java语法基础(十四)抽象类

    Java15-java语法基础(十四)抽象类 一.抽象类的作用 三个类都有"执行任务"的方法,分别在这三个类中进行定义,因此需要重复编写代码,降低了程序开发效率,且增加了程序出现错 ...

随机推荐

  1. Netty中BIO,NIO

    同步阻塞io(BIO).伪异步io(PIO).非阻塞io(NIO).异步io(AIO)的概念及区别? 同步阻塞io(BIO):服务器端与客户端通过三次握手后建立连接,连接成功,双方通过I/O进行同步阻 ...

  2. 学习JAVA 安装

    下载 JDK      Tomcat9     Apache     mod_jk 1.安装JDK 这里就说配置环境变量 添加环境变量 JAVA_HOME(就是jdk的安装路径) CLASSPATH( ...

  3. css3实现动画效果

    一.动画效果的常用属性 实现动画效果需要借助css3的下列属性:transform,transion,animation(具体可以参见教材) 二.动画效果实例 1)文字闪烁的动画效果 /*文字的闪烁效 ...

  4. LaunchImage命名与AppIcon命名(ios设置 启动图片和AppIcon图片)

    LaunchImage AppIcon 分别拖拉至Images.scassets  对应的LaunchImage和AppIcon就可以设置 启动图片和AppIcon图片

  5. Java基础之泛型——使用二叉树进行排序(TryBinaryTree)

    控制台程序. 1.实现针对容器类的基于集合的循环 为了让容器类类型的对象能够在基于集合的for循环中可用,类必须并且只需要满足一个要求——必须实现泛型接口java.lang.Iterable<& ...

  6. 前端构建工具gulpjs

    gulpjs是一个前端构建工具,与gruntjs相比,gulpjs无需写一大堆繁杂的配置参数,API也非常简单,学习起来很容易,而且gulpjs使用的是nodejs中stream来读取和操作数据,其速 ...

  7. Leetcode: Longest Absolute File Path

    Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...

  8. RESTful架构详解(转)

    1. 什么是REST REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移. 它首次出现在2000年Roy Fielding的 ...

  9. [编辑] 分享一些java视频

    1.官网:http://www.atguigu.com/,导航栏视频下载,根据自己的需求下载,对应的视频,其次可以下载相应的文档. 2.百度网盘: 链接: http://pan.baidu.com/s ...

  10. paper 22:kl-divergence(KL散度)实现代码

    这个函数很重要: function KL = kldiv(varValue,pVect1,pVect2,varargin) %KLDIV Kullback-Leibler or Jensen-Shan ...