Java进阶知识查漏补缺05
Java线程死锁:
package com.cjf.ThreadAppl; /** * Created with IntelliJ IDEA. * Description: * Author: Everything * Date: 2020-07-01 * Time: 20:48 */ //死锁问题 public class DeadLockTest { public static void main(String[] args) { StringBuffer s1 = new StringBuffer(); StringBuffer s2 = new StringBuffer(); new Thread(){ @Override public void run() { synchronized (s1){ s1.append("a"); s2.append("1"); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (s2){ s1.append("b"); s2.append("2"); System.out.println(s1); System.out.println(s2); } } } }.start(); new Thread(new Runnable() { @Override public void run() { synchronized (s2) { s1.append("c"); s2.append("3"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (s1) { s1.append("d"); s2.append("4"); System.out.println(s1); System.out.println(s2); } } } }).start(); } }
解决Java线程死锁,改进懒汉式单例模式
package com.cjf.ThreadAppl; /** * Created with IntelliJ IDEA. * Description: * Author: Everything * Date: 2020-07-01 * Time: 20:23 */ //改进懒汉式单例模式 public class SingletonSenior { } class Bank{ private Bank(){ } private static Bank instance = null; public static Bank getInstance() { //这种方式,会让后面的进程一直重复无用的判断工作,当前已经不能创建新的对象,直接进入return效率会更高 // synchronized (Bank.class) { // if (instance == null) { // instance = new Bank(); // } // return instance; // } //下面这种效率高 if(instance == null){ synchronized (Bank.class) { if (instance == null) { instance = new Bank(); } } } return instance; } }
使用Lock锁解决线程安全问题
package com.cjf.ThreadAppl; import sun.security.krb5.internal.Ticket; import javax.swing.plaf.SliderUI; import java.util.concurrent.locks.ReentrantLock; /** * Created with IntelliJ IDEA. * Description: * Author: Everything * Date: 2020-07-01 * Time: 21:12 */ //jdk5以后加入 //方法三:使用Lock锁解决线程安全问题 class Window implements Runnable{ private int ticket=100; //实例化一个ReentrantLock锁 private ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ try { //调用锁定方法lock lock.lock(); if(ticket > 0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } ticket--; System.out.println(Thread.currentThread().getName()+"售出票,余票"+ticket+"张"); }else { break; } }finally { //调用解锁方法 lock.unlock(); } } } } public class LockTest { public static void main(String[] args) { Window window1 = new Window(); Thread thread1 = new Thread(window1); Thread thread2 = new Thread(window1); Thread thread3 = new Thread(window1); thread1.setName("窗口一"); thread2.setName("窗口二"); thread3.setName("窗口三"); thread1.start(); thread2.start(); thread3.start(); } }