Java多线程基础

创建线程的主要方式

  1. 继承Thread类创建线程类(重点)
  2. 实现Runnable接口创建线程类(重点)
  3. 实现Callable接口或Future接口创建线程(了解)

1、前言

关于学习Java多线程,其中程序,进程和线程等重要概念及其关系在这里就不多赘述,之前操作系统也详细讲过,我就不再详细扩展,直接进入Java线程的学习吧!

此处分享一下Java1.8帮助文档(中文版),提取码: k26d

2、Thread类

2.1 Thread类实现Runnable接口

源码:

public
class Thread implements Runnable {
  /* Make sure registerNatives is the first thing <clinit> does. */
  private static native void registerNatives();
  static {
    registerNatives();
  }

  private volatile String name;
  private int            priority;
  private Thread         threadQ;
  private long           eetop;

  /* Whether or not to single_step this thread. */
  private boolean     single_step;
  ...
}

2.2 创建步骤:

将一个类声明为Thread的子类。 这个子类应该重写Thread类的run方法 。 然后可以分配并启动子类的实例

  • 自定义线程类继承Thread类
  • 重写run()方法,编写线程执行体
  • 创建线程对象,调用start()方法启动线程

2.2.1 测试

public class Thread1 extends Thread {

  @Override
  public void run() {
    // run方法线程体
    for (int i = 0; i < 20; i++) {
      System.out.print(String.format("%-3d", i) + "Hello    ");
    }
  }

  public static void main(String[] args) {
    // main方法主线程
    
    // 创建一个线程对象
    Thread1 thread1 = new Thread1();
    
    // 调用start方法开启线程
    thread1.start();
    
    for (int i = 0; i < 800; i++) {
      System.err.print(String.format("%-3d", i) + "World    ");
    }
  }
}

查看控制台输出:

注意:线程开启不一定立即执行,由CPU调度执行

调用start方法,是线程同时执行,交替执行。如果调用run方法,就是顺序执行。

2.2.2 案例:实现多线程同步下载图片

APACHE官网下载commons-io,导入项目Library

public class Thread2 extends Thread {
	
  private String url;		// Picture url
  private String path;
  private String name;	// Saved file name

  public Thread2(String url, String path, String name) {
    super();
    this.url = url;
    this.path = path;
    this.name = name;
  }

  @Override
  public void run() {
    WebDownloader webDownloader = new WebDownloader();
    webDownloader.downloader(url, path, name);
    System.out.println("Downloaded the file which name is " + name);
  }
	
  public static void main(String[] args) {
    String path = "src/com/newthread/img/";
    Thread2 t1 = new Thread2(
        "https://wx1.sinaimg.cn/orj360/67e231a6ly1geq8okovekj21hc0u0e42.jpg",
        path, "tower.jpg");
    Thread2 t2 = new Thread2(
        "https://wx1.sinaimg.cn/orj360/67e231a6ly1geq8oq8jx1j21hc0u0qse.jpg",
        path, "bike.jpg");
    Thread2 t3 = new Thread2(
        "https://wx1.sinaimg.cn/orj360/67e231a6ly1geq8on2u4gj21hc0u0ngj.jpg",
        path, "bridge.jpg");

    // simultaneous execution
    t1.start();
    t2.start();
    t3.start();
  }
}

// downloader
class WebDownloader{
  // download function
  public void downloader(String url, String path,String name) {
    try {
      FileUtils.copyURLToFile(new URL(url), new File(path + name));
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
      System.err.println("IO Exception...downloader function has a problem!");
    }
  }
}

结果:

3、Runnable接口

3.1 Runnable接口

声明实现类Runnable接口。 那个类然后实现了run方法。 然后可以分配类的实例,在创建Thread时作为参数传递,并启动。

源码:

public
class Thread implements Runnable {
  /* Make sure registerNatives is the first thing <clinit> does. */
  private static native void registerNatives();
  static {
    registerNatives();
  }
  
  ...
    
  public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
  }
  ...
}

实现Runnable接口创建的线程,不能通过run或start方法来启动。在Thread类中有一个构造器,这个构造器接收一个Runnable接口的实现类对象,构造Thread线程类对象,然后使用这个线程类对象调用start方法启动我们的线程。

3.2 创建步骤

  • 自定义线程类实现Runnable接口
  • 实现run()方法,编写线程执行体
  • 创建线程对象,调用start()方法启动线程

推荐使用Runnable对象,因为Java单继承的局限性

public class Thread3 implements Runnable {
  @Override
  public void run() {
    // run方法线程体
    for (int i = 0; i < 20; i++) {
      System.out.print(String.format("%-3d", i) + "Hello    ");
    }
  }

  public static void main(String[] args) {
    // main方法主线程
    
    // 创建Runnable接口的实现类对象
    Thread3 thread3 = new Thread3();
    
//    Thread thread = new Thread(thread3);
//    thread.start();
    
    new Thread(thread3).start();
    
    for (int i = 0; i < 800; i++) {
      System.err.print(String.format("%-3d", i) + "World    ");
    }
  }
}

3.3 对比

  • 继承Thread类
    • 子类继承Thread类具有多线程能力
    • 启动线程:子类对象.start()
    • 不建议使用:避免OOP单继承局限
  • 实现Runnable接口
    • 子类实现Runnable接口具有多线程能力
    • 启动线程:传入目标对象+Thread对象.start()
    • 推荐使用:避免单继承局限性,灵活方便,方便同一对象被多个线程使用

4、Callable接口(了解即可)

4.1 源码:

@FunctionalInterface
public interface Callable<V> {
  /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
  V call() throws Exception;
}

从源码可以看出,Callable接口中的call()方法是有返回值的,是一个泛型,和Future、FutureTask配合可以用来获取异步执行的结果。

这其实是很有用的一个特性,因为多线程相比单线程更难、更复杂的一个重要原因就是因为多线程充满着未知性,某条线程是否执行了?某条线程执行了多久?某条线程执行的时候我们期望的数据是否已经赋值完毕?无法得知,我们能做的只是等待这条多线程的任务执行完毕而已。而Callable+Future/FutureTask却可以获取多线程运行的结果,可以在等待时间太长没获取到需要的数据的情况下取消该线程的任务。

4.2 创建步骤

  • 实现Callable接口,需要返回值类型

  • 重写call方法,需要抛出异常

  • 创建目标对象

  • 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);

  • 提交执行:Future< Boolean> result1 = ser.submit(1);

  • 获取结果:boolean r1= result1.get();

  • 关闭服务:ser.shutdownNow();

public class Callable1 implements Callable<Boolean>{

  @Override
  public Boolean call() throws Exception {
    for (int i = 0; i < 20; i++) {
      System.out.println(String.format("%-3d", i) +
            Thread.currentThread().getName());
    }
    return true;
  }
	
  public static void main(String[] args) 
    throws InterruptedException, ExecutionException {

    Callable1 callable1 = new Callable1();
    Callable1 callable2 = new Callable1();
    Callable1 callable3 = new Callable1();
    
    // 创建执行服务
    ExecutorService ser = Executors.newFixedThreadPool(3);

    // 提交执行
    Future<Boolean> result1 = ser.submit(callable1);
    Future<Boolean> result2 = ser.submit(callable2);
    Future<Boolean> result3 = ser.submit(callable3);
    
    // 获取结果
    boolean r1= result1.get();
    boolean r2= result2.get();
    boolean r3= result3.get();
    System.out.println(r1 + " "+ r2 + " " + r3);

    // 关闭服务
    ser.shutdownNow();
  }
}

5、静态代理模式

5.1 内容

真实角色,代理角色;真实角色和代理角色要实现同一个接口,代理角色要持有真实角色的引用

在Java中线程的设计使用了静态代理设计模式,其中自定义线程类实现Runable接口,Thread类也实现了Runalbe接口,在创建子线程的时候,传入了自定义线程类的引用,再通过调用start()方法,调用自定义线程对象的run()方法。实现了线程的并发执行。

Thread对象调用线程的start()方法,在内部调用了真实角色的run()方法。

5.2 设计

代码结构由三部分组成

  • 接口:主题

  • 代理类

  • 被代理类

实现方式:代理类和被代理类要实现同一个主题接口,而且代理类中要有一个被代理类的属性(target),这样才能把核心业务逻辑交还给被代理类完成;而一些与核心业务逻辑无关的逻辑,并且需求是多变的,那么这些逻辑就可以交给代理类来完成。

代理对象可以做很多真实对象做不了的事情,真实对象专注做自己的事情

public class StaticProxy {
  public static void main(String[] args) {
    SpringPioneer springPioneer = new SpringPioneer(new Programmer());
    springPioneer.Deploy();
  }
}

interface SpringBootFrame {
  // 接口主题:框架整合部署
  void Deploy();
}

// 真实角色,程序员
class Programmer implements SpringBootFrame{

  @Override
  public void Deploy() {
    System.out.println("Programmer SpringBoot deployed successfully!");
  }
}

// 代理角色,SpringBoot的作者,帮我们简化开发
class SpringPioneer implements SpringBootFrame{
	
  // 代理谁-->真实目标角色
  private SpringBootFrame target;

  public SpringPioneer(SpringBootFrame target) {
    this.target = target;
  }

  @Override
  public void Deploy() {
    before();
    this.target.Deploy();	// 这就是真实对象
    after();
  }

  private void before() {
    System.out.println("研发出这个SpringBoot框架,并开源。");
  }

  private void after() {
    System.out.println("不断推出新的特性。");
  }
}

6、Lambda表达式

函数式编程的概念

6.1 为什么要使用lambda表达式?

避免匿名内部类定义过多,代码简洁,去掉无意义代码,核心逻辑。

理解Functional Interface(函数式接口)是学习Java8 lambda表达式的关键。

函数式接口的定义:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。

public interface Runnable {
  public abstract void run();
}

对于函数式接口,我们可以通过lambda表达式来创建接口的对象。

public class lambda1 {
  // 3.静态内部类
  static class StaticEntityLike implements Like {
    @Override
    public void lambda() {
      System.out.println("Static likes lambda!");
    }
  }

  public static void main(String[] args) {
    Like entityLike = new EntityLike();
    entityLike.lambda();

    Like staticEntityLike = new StaticEntityLike();
    staticEntityLike.lambda();

    // 4.局部内部类
    class InternalEntityLike implements Like {
      @Override
      public void lambda() {
        System.out.println("Internal likes lambda!");
      }
    }

    Like internalEntityLike = new InternalEntityLike();
    internalEntityLike.lambda();

    // 5.匿名内部类,没有类的名称,必须借助接口或者父类
    Like anonymousEntityLike = new Like() {
      @Override
      public void lambda() {
        System.out.println("Anonymous likes lambda!");
      }
    };
    anonymousEntityLike.lambda();

    // 6.用lambda简化
    Like lambdaLike = () -> {
      System.out.println("Lambda likes lambda!");
    };
    lambdaLike.lambda();

//    new Like(()->System.out.println("Lambda likes lambda!")).lambda();

    // 7.带参数的
    Love lambdaLove = (int t) -> {
      System.out.println("Lambda loves you " + t + " times!");
    };
    lambdaLove.time(520);

    // 7.1简化去掉参数类型
    Love love1 = (t) -> {
      System.out.println("Lambda loves you " + t + " times!");
    };
    love1.time(521);

    // 7.2简化去掉括号
    Love love2 = t -> {
      System.out.println("Lambda loves you " + t + " times!");
    };
    love2.time(522);

    // 7.3简化去掉花括号
    // lambda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹
    Love love3 = t -> System.out.println("Lambda loves you " + t + " times!");
    love3.time(523);
  }
}

// 1.定义一个函数式接口
interface Like {
  void lambda();
}

// 2.实现类
class EntityLike implements Like {
  @Override
  public void lambda() {
    System.out.println("I like lambda!");
    
  }
}

// 带参数的
interface Love {
  void time(int t);
}

多个参数可以去掉参数类型,再简化就必须加上括号(a, b)->{};

7、线程

7.1 线程状态

创建状态(new):Thread t = new Thread();,线程对象一旦创建,就进入到了新生状态。

就绪状态:当调用start()方法,线程立即进入就绪状态,但不意味着立即调度执行。

运行状态:CPU调度进入运行状态线程才真正执行线程体的代码块。

阻塞状态:当调用sleep()wait()或同步锁定时,线程进入阻塞状态就是代码不往下执行,阻塞
事件解除后,重新进入就绪状态,等待cpu调度执行。

死亡状态(dead):线程中断或者结束,一旦进入死亡状态,就不能再次启动

7.2 线程方法

方法 说明
setPriority(int newPriority) 设置当前线程的优先级
static void sleep(long millis) 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)。休眠的线程进入阻塞状态。
void join() 调用join方法的线程强制执行,其他线程处于阻塞状态,等该线程执行完后,其他线程再执行。有可能被外界中断产生InterruptedException中断异常。
static void yield() 调用yield方法的线程,(暂停当前执行的线程对象)会礼让其他线程先运行。(大概率其他线程先运行,小概率自己还会运行)
void interrupt() 中断线程,不建议使用
boolean isAlive() 判断线程是否处于活动状态 (线程调用start后,即处于活动状态)

7.3 停止线程

  • 不推荐使用JDK提供的stop()destroy()方法。(已废弃)

    public
    class Thread implements Runnable {
      ...
      @Deprecated
        public final void stop() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
          checkAccess();
          if (this != Thread.currentThread()) {
            security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
          }
        }
        // A zero status value corresponds to "NEW", it can't change to
        // not-NEW because we hold the lock.
        if (threadStatus != 0) {
          resume(); // Wake up thread if it was suspended; no-op otherwise
        }
    
        // The VM can handle all thread states
        stop0(new ThreadDeath());
      }
      ...
      @Deprecated
        public void destroy() {
        throw new NoSuchMethodError();
      }
      ...
    }
    
  • 推荐线程自己停止下来,建议使用一个标志位进行终止变量当flag=false,则终止线程运行。

    public class TestStop implements Runnable {
      // 1.设置一个标志位
    	private boolean flag = true;
    
      @Override
      public void run() {
        int i=0;
        while (flag) {
          System.out.println("run...Thread..."+i++);
        }
      }
    
      // 2.设置一个公开的方法停止线程,转换标志位
      public void stop() {
        this.flag = false;
      }
    
      public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
    
        for (int i = 0; i < 200; i++) {
          System.out.println("main...Thread..."+i);
          if(i==100) {
            // 调用stop方法停止线程
            testStop.stop();
            System.out.println("run...Thread...stoped...");
          }
        }
      }
    }
    

    结果:线程停止,main线程继续执行到结束

7.4 线程休眠

sleep(时间)指定当前线程阻塞的毫秒数;sleep存在异常Interrupted Exception;sleep时间达到后线程进入就绪状态;sleep可以模拟网络延时,倒计时等;每一个对象都有一个锁,sleep不会释放锁。

示例:

// 模拟倒计时
public class TestSleep2 {
  public static void main(String[] args) {
    try {
      tenDown();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // 打印当前系统时间
    Date startTime = new Date(System.currentTimeMillis());	// 获取当前系统时间

    System.out.println("Start printing system time...");

    while (true) {
      try {
        Thread.sleep(1000);
        System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
        startTime = new Date(System.currentTimeMillis());	// 更新时间
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public static void tenDown() throws InterruptedException {
    int num=10;
    while (true) {
      Thread.sleep(1000);
      System.out.println(num--);
      if (num<=0) {
        break;
      }
    }
	}
}

7.4 线程礼让

礼让线程,让当前正在执行的线程暂停,但不阻塞;将线程从运行状态转为就绪状态;让cpu重新调度,礼让不一定成功!看CPU心情。

示例:

public class TestYield {
  public static void main(String[] args) {
    MyYield myYield = new MyYield();
    
    new Thread(myYield, "a").start();
    new Thread(myYield, "b").start();
  }
}

class MyYield implements Runnable{
  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName()+"Thread starts...");
    Thread.yield();    // 礼让
    System.out.println(Thread.currentThread().getName()+"Thread ends...");
  }
}

7.5 线程强制执行

join()合并程序,待此线程执行完成后,再执行其他线程,其他线程阻塞。可以想象为插队。

示例:

public class TestJoin implements Runnable {

  @Override
  public void run() {
    for (int i = 0; i < 100; i++) {
      System.out.println("VIP thread comes..."+i);
    }
  }

  public static void main(String[] args) {
    TestJoin testJoin = new TestJoin();
    Thread thisThread = new Thread(testJoin);
    thisThread.start();
    
    for (int i = 0; i < 200; i++) {
      if (i==90) {
        try {
          thisThread.join();	// 插队
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println("main Thread..."+i);
    }
  }
}

取一个运行结果:

main Thread...0
VIP thread comes...0
main Thread...1
VIP thread comes...1
VIP thread comes...2
VIP thread comes...3
VIP thread comes...4
VIP thread comes...5
...
main Thread...87
main Thread...88
main Thread...89
VIP thread comes...19
VIP thread comes...20
VIP thread comes...21
VIP thread comes...22
VIP thread comes...23
VIP thread comes...24
...
VIP thread comes...98
VIP thread comes...99
main Thread...90
main Thread...91
main Thread...92
main Thread...93

在插队之前,2线程并行,当调用join()后,这个线程即成为VIP,只能等VIP线程执行结束,其他线程才能继续执行。

7.6 线程状态

线程状态State是枚举类型,有5个状态,在中文帮助文档中有声明。

Thread.java源码:

public
class Thread implements Runnable {
  ...
  public enum State {
    NEW,

    RUNNABLE,

    BLOCKED,

    WAITING,

    TIMED_WAITING,

    TERMINATED;
  }

  public State getState() {
    return sun.misc.VM.toThreadState(threadStatus);
  }
  ...
}

示例:

public class TestState {
  public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(()->{
      for (int i = 0; i < 5; i++) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println("\\\\\\");
    });
    
    // 观察状态
    Thread.State state = thread.getState();
    System.out.println(state);	// NEW
    
    // 启动
    thread.start();
    state = thread.getState();
    System.out.println(state);	// RUN
    
    while (state != Thread.State.TERMINATED) {	// 只要线程不终止就一直输出状态
      Thread.sleep(100);
      state = thread.getState();	// 更新状态
      System.out.println(state);
      
    }
  }
}

7.7 线程优先级

Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行;线程的优先级用数字表示,范围从1-10。

Thread.java源码:

public
class Thread implements Runnable {
  ...
  public final static int MIN_PRIORITY = 1;

  public final static int NORM_PRIORITY = 5;

  public final static int MAX_PRIORITY = 10;
  ...
  public final void setPriority(int newPriority) {
    ThreadGroup g;
    checkAccess();
    if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
      throw new IllegalArgumentException();
    }
    if((g = getThreadGroup()) != null) {
      if (newPriority > g.getMaxPriority()) {
        newPriority = g.getMaxPriority();
      }
      setPriority0(priority = newPriority);
    }
  }
  ...
}

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。

示例:

public class TestPriority {
  public static void main(String[] args) {
    // 主线程默认优先级
    System.out.println(
        Thread.currentThread().getName() +
        "-->"+Thread.currentThread().getPriority()
    );
    
    MyPriority myPriority = new MyPriority();
    
    Thread t1 = new Thread(myPriority);
    Thread t2 = new Thread(myPriority);
    Thread t3 = new Thread(myPriority);
    Thread t4 = new Thread(myPriority);
    Thread t5 = new Thread(myPriority);

    t1.start();
    
    t2.setPriority(2);	// 先设置优先级再启动
    t2.start();
    
    t3.setPriority(Thread.MAX_PRIORITY);
    t3.start();
    
    try {
      t4.setPriority(-1);
      t4.start();
      
      t5.setPriority(11);
      t5.start();
    } catch (Exception e) {
      System.err.println(e);
    }
  }
}

class MyPriority implements Runnable {
  @Override
  public void run() {
    System.out.println(
        Thread.currentThread().getName()+"-->" +
        Thread.currentThread().getPriority()
    );
  }
}

取一个运行结果:

main-->5
java.lang.IllegalArgumentException
Thread-0-->5
Thread-2-->10
Thread-1-->2

总是主线程mian限制性,优先级低的也可能比高的优先执行。

7.8 守护(daemon)线程

线程分为用户线程和守护线程;虚拟机必须确保用户线程(main线程)执行完毕;虚拟机不用等待守护线程执行完毕;如后台记录操作日志,监控内存垃圾回收等。

示例:

public class TestDaemon {
  public static void main(String[] args) {
    God god = new God();
    Man man = new Man();
    
    Thread thread = new Thread(god);
    thread.setDaemon(true);  // 默认false表示用户线程,正常的线程都是用户线程
    
    thread.start();  // 守护线程启动
    
    new Thread(man).start();  // 用户线程挺停止
  }
}

class God implements Runnable {
  @Override
  public void run() {
    while (true) {
      System.out.println("God bless you!");
    }
  }
}

class Man implements Runnable {
  @Override
  public void run() {
    for (int i = 0; i < 100; i++) {
      System.out.println("Hello World!");
    }
    System.err.println("Goodbye World!");
  }
}

看似god线程会一直循环执行下去,但它是守护线程,man线程执行结束后,守护线程等一会也会结束,因为虚拟机还会运行一会儿。

8、线程同步

多个线程操作同一个资源。

并发:同一个对象被多个线程同时操作。

处理多线程问题时,多个线程访问同—个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步。线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。

8.1 队列和锁

由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁(锁是对象的),将会独占资源。其他线程必须等待这个线程使用后释放锁即可。存在以下问题:

  • 一个线程持有锁会导致其他所有需要此锁的线程挂起

  • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换调度延时,引起性能问题

  • 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题

8.2 同步方法

  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法synchronized方法和synchronized块

    同步方法: public synchronized void method(int args)

  • synchronized方法控制对“对象"的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行

    缺陷:若将一个大的方法申明为 synchronized将会影响效率

  • 弊端:需要锁太多,浪费资源

8.3 同步块

  • 同步块:synchronized(obj){}

  • obj称之为同步监视器

    • obj可以是任何对象,但是推荐使用共享资源作为同步监视器
    • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class[反射中讲解]
  • 同步监视器的执行过程

    • 第一个线程访问,锁定同步监视器,执行其中代码
    • 第二个线程访问,发现同步监视器被锁定,无法访问
    • 第一个线程访问完毕,解锁同步监视器
    • 第二个线程访问,发现同步监视器没有锁,然后锁定并访问

案例:

public class Bank {
  public static void main(String[] args) {
    Account account = new Account(100, "Deposit");
    
    Drawing husband = new Drawing(account, 50, "husband");
    Drawing wife = new Drawing(account, 100, "wife");
    
    husband.start();
    wife.start();
  }
}

class Account {
  int money;
  String name;

  public Account(int money, String name) {
    this.money = money;
    this.name = name;
  }
}

class Drawing extends Thread {
  Account account;

  int drawingMoney;

  int nowMoney;

  public Drawing(Account account, int drawingMoney, String name) {
    super(name);
    this.account = account;
    this.drawingMoney = drawingMoney;
  }
	
  // @Override
  // public synchronized void run() {
  //   if(account.money-drawingMoney<0) {
  //     System.out.println(Thread.currentThread().getName()+" Money is not enough!");
  //     return;
  //   }
    
  //   try {
  //     Thread.sleep(1000);
  //   } catch (InterruptedException e) {
  //     e.printStackTrace();
  //   }
  //   // 卡内余额
  //   account.money = account.money - drawingMoney;
  //   // 手里的现金
  //   nowMoney = nowMoney + drawingMoney;
    
  //   System.out.println(account.name + " balance is "+account.money);
  //   System.out.println(this.getName()+"'s cash now is "+nowMoney);
  // }

  @Override
  public void run() {
    synchronized (account) {
      if(account.money-drawingMoney<0) {
        System.out.println(Thread.currentThread().getName()+" Money is not enough!");
        return;
      }
      
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      
      account.money = account.money - drawingMoney;

      nowMoney = nowMoney + drawingMoney;
      
      System.out.println(account.name + " balance is "+account.money);
      System.out.println(this.getName()+"'s cash now is "+nowMoney);
    }
  }
}

这里要注意了:同步块指定锁住的对象,可以锁住任何对象。如果用上面的方法将run方法上锁,锁住的是husband和wife对象,也就是有两把锁了(2个线程2把锁)。只能用下面的方法锁住变化的量,才有用。

List等常见数据集合是非安全的,JUC(java.util.concurrent包)中提供了CopyOnWriteArrayList等安全类型的集合。

9、锁

9.1 死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。

public class DeadLock {
  public static void main(String[] args) {
    Makeup girl1 = new Makeup(0, "Marry");
    Makeup girl2 = new Makeup(1, "Lisa");
    
    girl1.start();
    girl2.start();
  }
}

class Lipstick{

}

class Mirror {

}

class Makeup extends Thread {

  // 用static保证资源只有一份儿
  private static Lipstick lipstick = new Lipstick();
  private static Mirror mirror = new Mirror();
  int choice;
  String name;	// 化妆的人

  public Makeup(int choice, String name) {
    this.choice = choice;
    this.name = name;
  }

  @Override
  public void run() {
    try {
      startMakeup();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  // 化妆,互相持有对方的锁,就是需要拿到对方的资源
  // private void startMakeup() throws InterruptedException {
  //   if (choice==0) {
  //     synchronized (lipstick) {	// 获得口红的锁
  //       System.out.println(this.name+" got the lipstick!");
  //       Thread.sleep(1000);
  //       synchronized (mirror) {	// 1秒钟后向获得镜子
  //         System.out.println(this.name+" got the mirror!");
  //       }
  //     }
  //   } else {
  //     synchronized (mirror) {
  //       System.out.println(this.name+" got the mirror!");
  //       Thread.sleep(1000);
  //       synchronized (lipstick) {
  //         System.out.println(this.name+" got the lipstick!");
  //       }
  //     }
  //   }
  //   // 比如选择0时,只有当得到镜子后才会释放口红的锁,就会死锁
  // }

  private void startMakeup() throws InterruptedException {
    if (choice==0) {
      synchronized (lipstick) {	// 获得口红的锁
        System.out.println(this.name+" got the lipstick!");
        Thread.sleep(1000);
      }
      synchronized (mirror) {	// 1秒钟后向获得镜子
        System.out.println(this.name+" got the mirror!");
      }
    } else {
      synchronized (mirror) {
        System.out.println(this.name+" got the mirror!");
        Thread.sleep(1000);
      }
      synchronized (lipstick) {
        System.out.println(this.name+" got the lipstick!");
      }
    }
    // 这样做就是当口红用完口红的锁就释放
  }
}

结合操作系统死锁产生的条件和避免死锁的方式。

9.2 Lock(锁)

  • 从JDK5.0开始,Java提供了更强大的线程同步机制:通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当

  • java.utll.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,毎次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象

  • ReentrantLock(可重入锁)类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是Reentrantlock,可以显式加锁、释放锁。

9.3 synchronized和Lock的对比

  • Lock是显式锁(手动开启和关闭锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动释放

  • Lock只有代码块锁,synchronized有代码块锁和方法锁

  • 使用Lock锁,JwM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)

  • 优先使用顺序:Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)

10、线程协作(线程通信)

在生产者消费者问题中,仅有synchronized是不够的

  • synchronized可阻止并发更新同一个共享资源,实现了同步

  • synchronized不能用来实现不同线程之间的消息传递(通信)

Java提供了几个方法解决线程之间的通信问题

方法名 作用
wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁
wait(long timeout) 指定等待的毫秒数
notify() 唤醒一个处于等待状态的线程
notifyAll() 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度

注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用否则会抛出异常IlegalMonitorState Exception

10.1 解决方式1:管程法

并发协作模型“生产者/消费者模式”-->管程法

  • 生产者:负责生产数据的模块(可能是方法,对象,线程,进程)

  • 消费者:负责处理数据的模块(可能是方法,对象,线程,进程)

  • 缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区“

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据

public class TestProductorCustomer {
  public static void main(String[] args) {
    Buffer buffer = new Buffer();
    
    new Productor(buffer).start();
    new Customer(buffer).start();
  }
}

// 生产者
class Productor extends Thread {
  // 需要一个容器
  Buffer buffer;

  public Productor(Buffer buffer) {
    this.buffer = buffer;
  }

  // 生产
  @Override
  public void run() {
    for (int i = 1; i < 100; i++) {
      buffer.push(new Goods(i));
      System.out.println("生产了第"+i+"个商品!");
    }
  }
}

// 消费者
class Customer extends Thread {
  Buffer buffer;

  public Customer(Buffer buffer) {
    this.buffer = buffer;
  }

  // 消费
  @Override
  public void run() {
    for (int i = 1; i < 100; i++) {
      System.out.println("消费了第" + buffer.pop().getID() + "个商品!");
    }
  }
}

// 产品
class Goods extends Thread {
  private int ID;

  public Goods(int id) {
    this.ID = id;
  }

  public int getID() {
    return ID;
  }
}

// 缓冲区
class Buffer extends Thread {
  // 需要一个容器大小
  Goods[] goods = new Goods[10];

  int count=0;

  // 生产者放入产品
  public synchronized void push(Goods good) {
    // 如果容器满了,就需要等待消费者消费
    if(count==goods.length) {
      // 通知消费者消费,生产等待
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    
    // 如果没有满就需要放入产品
    goods[count] = good;
    count++;
    
    // 可以通知消费者消费了
    this.notifyAll();
  }

  // 消费者消费产品
  public synchronized Goods pop() {
    // 如果容器是否为空
    if(count==0) {
      // 通知生产者生产,消费等待
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    // 如果可以消费
    count--;
    Goods good = goods[count];

    // 可以通知生产者生产了
    this.notifyAll();
    return good;
  }
}

10.2 解决方式2:信号灯法

就是长度为1的管程法

public class ProductorCustomerUsingSignal {
  public static void main(String[] args) {
    Show show = new Show();
    new Actor(show).start();
    new Audience(show).start();
  }
}

// 生产者演员
class Actor extends Thread {
  private Show show;
  public Actor(Show show) {
    this.show = show;
  }

  @Override
  public void run() {
    for (int i = 0; i < 20; i++) {
      if (i%2==0) {
        this.show.play("Happy Camp!");
      } else {
        this.show.play("TikTok!");
      }
    }
  }
}

// 消费者观众
class Audience extends Thread {
  private Show show;
  public Audience(Show show) {
    this.show = show;
  }

  @Override
  public void run() {
    for (int i = 0; i < 20; i++) {
      this.show.watch();
    }
  }
}

// 资源节目
class Show {
  // 演员表演,观众等待	T
  // 观众观看,演员等待	F
  private boolean flag = true;
  String display;	// 表演的节目

  // 表演
  public synchronized void play(String display) {
    if (!flag) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Actors show the "+display);
    // 通知观众观看
    this.notifyAll();
    this.display = display;
    this.flag = !this.flag;
  }

  // 表演
  public synchronized void watch() {
    if (flag) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Audience watch the "+display);
    // 通知演员表演
    this.notifyAll();
    this.flag = !this.flag;
  }
}

11、线程池

背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。

思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具(共享单车)。

优势:

  • 提高响应速度(减少了创建新线程的时间)

  • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)

  • 便于线程管理(…)

    • core Poolsize:核心池的大小
    • maximumPoolsize:最大线程数
    • keepAlive Time:线程没有任务时最多保持多长时间后会终止
public class TestPool {
  public static void main(String[] args) {
    // 1.创建服务,创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    
    executorService.execute(new PoolThread());
    executorService.execute(new PoolThread());
    executorService.execute(new PoolThread());
    executorService.execute(new PoolThread());
    
    // 2.关闭连接
    executorService.shutdown();
  }
}

class PoolThread implements Runnable {
  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName());
  }
}
  • JDK5.0起提供了线程池相关API:Executor Service和Executors

  • Executor Service:真正的线程池接口。常见子类 ThreadPoolExecutor

    • void execute( Runnable command):执行任务命令,没有返回值,一般用来执
      行 Runnable
    • <T> Future<T> submit( Callable<T>task):执行任务,有返回值,一般又来执行
      Callable(上面我们介绍Callable接口时测试过)
    • void shutdown():关闭连接池
  • Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池

posted @ 2020-09-16 15:18  mysteryguest  阅读(284)  评论(0编辑  收藏  举报