线程的生命周期
JDK中用Thread.State类定义了线程的几种状态
要想实现多线程,必须在主线程中创建新的线程对象。java语言使用Thread类及其子类的对象来表示线程,在它的一个完整的生命周期中通常要经历如下的五种状态。
新建
当一个Thread类或其子类的对象被声明并创建时,新生的线程对象处理新建状态。
就绪
处于新建状态的线程被 start()后,将进入线程队列等待CPU的时间片,此时它已经具备了运行条件,知识还没分配到CPU的资源。
运行
当就绪的线程被调度并获得CPU资源时,便进入运行状态,run()方法定义了线程的操作和功能。
阻塞
在某种特殊的情况下,被人为的挂起或执行输入输出操作时,让出CPU并临时中止自己的执行,进入阻塞状态。
死亡
线程完成了它全部的工作或线程被提前强制性的中止或出现异常导致结束。
线程的同步
问题的提出(模拟火车站售票程序,开启三个售票窗口)
class Windows1 implements Runnable{private int ticket=100;@Overridepublic void run() {while (true){if (ticket>0) {try {//模拟网络延时等情况Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+": 卖票,票号为:"+ticket);ticket--;}else{break;}}}}public class WindowsTest1 {public static void main(String[] args) {Windows1 windows1=new Windows1();Thread thread = new Thread(windows1);Thread thread2 = new Thread(windows1);Thread thread3 = new Thread(windows1);thread.setName("窗口1");thread2.setName("窗口2");thread3.setName("窗口3");thread.setPriority(Thread.MIN_PRIORITY);thread3.setPriority(Thread.MAX_PRIORITY);thread.start();thread2.start();thread3.start();}}
执行结果
问题:卖票过程中,出现了重票(上图未出现)、错票(出现0,-1的票号),表示出现了线程安全问题
问题出现的原因:当某个线程操作车票的过程当中,尚未完成操作时,其他线程参与进来,也来操作车票。(当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来。导致共享数据的错误)
解决办法:对多线程操作共享数据的情况,只能让一个线程都执行完所有对该数据的操作,同时在执行过程中,其他线程不可以参与操作。
- 当一个线程a在操作ticket的时候,其他的线程不能参与进来。直到线程a操作完ticket时,其他的线程才可以开始操作ticket。这种情况下,即使线程a出现了阻塞,也不能被改变。
- 在java当中通过同步机制,来解决线程的安全问题。
方式一:同步代码块(synchronized)
synchronized(同步监视器){//需要被同步的代码(也就是操作共享数据的代码)}
- 同步监视器,俗称,锁。任何一个类的对象都可以充当锁。(不能包多了代码块,也不能包少了代码块)
- 要求:多个线程必须共用同一把锁(共用同一个对象)
/*** 使用同步代码块的方式解决实现Runnable接口的线程安全问题*/class Windows1 implements Runnable{private int ticket=100;Object object=new Object();@Overridepublic void run() {while (true){//使用反射创建的Class对象也是唯一,或者使用this当前对象也是唯一//synchronized(Windows1.class){//synchronized(this){synchronized(object) {if (ticket > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + ticket);ticket--;} else {break;}}}}}public class WindowsTest1 {public static void main(String[] args) {Windows1 windows1=new Windows1();Thread thread = new Thread(windows1);Thread thread2 = new Thread(windows1);Thread thread3 = new Thread(windows1);thread.setName("窗口1");thread2.setName("窗口2");thread3.setName("窗口3");thread.setPriority(Thread.MIN_PRIORITY);thread3.setPriority(Thread.MAX_PRIORITY);thread.start();thread2.start();thread3.start();}}
/*** 使用同步代码块的方式解决继承Thread类的线程安全问题*/class Windows extends Thread{private static int ticket=100;@Overridepublic void run() {while (true) {synchronized (Windows.class) {if (ticket > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(getName() + ": 卖票,票号为:" + ticket);ticket--;} else {break;}}}}}public class WindowsTest {public static void main(String[] args) {Windows w1=new Windows();Windows w2=new Windows();Windows w3=new Windows();w1.setName("窗口1");w2.setName("窗口2");w3.setName("窗口3");w1.start();w2.start();w3.start();}}
方式二:同步方法
如果操作共享数据的代码完整的声明在一个方法中,我们不妨将此方法声明为同步的。
注意:
1、同步方法仍然涉及到同步监视器,只是不需要我们显示的声明。
2、非静态的同步方法,同步监视器是:this;静态的同步方法,同步监视器是:当前类本身。
/**** 使用同步方法解决实现Runnable接口的线程安全问题*/class Windows2 implements Runnable{private int ticket=100;Object object=new Object();@Overridepublic void run() {while (true){//使用反射创建的Class对象也是唯一//synchronized(Windows1.class){show();}}private synchronized void show(){ //同步监视器:thisif (ticket > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + ticket);ticket--;}}}public class WindowsTest2 {public static void main(String[] args) {Windows2 windows2=new Windows2();Thread thread = new Thread(windows2);Thread thread2 = new Thread(windows2);Thread thread3 = new Thread(windows2);thread.setName("窗口1");thread2.setName("窗口2");thread3.setName("窗口3");thread.setPriority(Thread.MIN_PRIORITY);thread3.setPriority(Thread.MAX_PRIORITY);thread.start();thread2.start();thread3.start();}}
/**** 使用同步方法解决继承Thread类的线程安全问题*/class Windows3 extends Thread{private static int ticket=100;@Overridepublic void run() {while (true) {show();}}private static synchronized void show(){ //同步监视器:Windows3.class//private synchronized void show(){ //此种解决方式是错误的if (ticket > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + ticket);ticket--;}}}public class WindowsTest3 {public static void main(String[] args) {Windows3 w1=new Windows3();Windows3 w2=new Windows3();Windows3 w3=new Windows3();w1.setName("窗口1");w2.setName("窗口2");w3.setName("窗口3");w1.start();w2.start();w3.start();}}
修改单例模式中的懒汉式线程安全问题
/**** 修改单例模式中的线程安全问题*/public class Bank {private Bank(){};private static Bank instance=null;public static Bank getInstance(){//方式一:效率较差// 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;}}
释放锁的操作
- 当前线程的同步方法、同步代码块执行结束。
- 当前线程在同步代码块、同步方法中遇到了break、return终止了该代码块、该方法的继续执行
- 当前线程在同步代码块、同步方法中出现了未处理的Error或Exception,导致异常结束。
- 当前线程在同步代码快、同步方法中执行了线程对象的wait()方法,当前线程暂停,并释放锁。
不会释放锁的操作
- 线程执行同步代码块或同步方法的时,程序调用Thread.sleep()、Thread.yield()方法暂停当前线程的执行
- 线程执行同步代码块时,其他线程调用了该线程的suspend()方法,将该线程挂起,该线程不会释放锁(同步监视器)
- 应该避免使用suspend()和resume()来控制线程
线程的死锁问题
- 1、死锁的理解:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
- 2、说明:出现死锁后,不会出现异常、不会出现提示,只是所有的线程都处于阻塞状态,无法继续执行
- 3、我们使用同步时,要避免出现死锁
/*** 演示线程的死锁问题** 1、死锁的理解:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁* 2、说明:出现死锁后,不会出现异常、不会出现提示,只是所有的线程都处于阻塞状态,无法继续执行* 3、我们使用同步时,要避免出现死锁**/public class DeadLock1 {public static void main(String[] args) {StringBuffer s1=new StringBuffer();StringBuffer s2=new StringBuffer();new Thread(){@Overridepublic void run() {//先锁s1synchronized(s1){s1.append("a");s2.append("1");//添加阻塞,增大出现死锁的概率try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}//再锁s2synchronized (s2){s1.append("2");s2.append("b");System.out.println(s1);System.out.println(s2);}}}}.start();new Thread(new Runnable() {@Overridepublic void run() {//先锁s2synchronized (s2){s1.append("c");s2.append("3");try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}//再锁s1synchronized (s1){s1.append("d");s2.append("4");System.out.println(s1);System.out.println(s2);}}}}).start();}}
class A {public synchronized void foo(B b) {System.out.println("当前线程名: " + Thread.currentThread().getName()+ " 进入了A实例的foo方法"); // ①try {Thread.sleep(200);} catch (InterruptedException ex) {ex.printStackTrace();}System.out.println("当前线程名: " + Thread.currentThread().getName()+ " 企图调用B实例的last方法"); // ③b.last();}public synchronized void last() {System.out.println("进入了A类的last方法内部");}}class B {public synchronized void bar(A a) {System.out.println("当前线程名: " + Thread.currentThread().getName()+ " 进入了B实例的bar方法"); // ②try {Thread.sleep(200);} catch (InterruptedException ex) {ex.printStackTrace();}System.out.println("当前线程名: " + Thread.currentThread().getName()+ " 企图调用A实例的last方法"); // ④a.last();}public synchronized void last() {System.out.println("进入了B类的last方法内部");}}public class DeadLock implements Runnable {A a = new A();B b = new B();public void init() {Thread.currentThread().setName("主线程");// 调用a对象的foo方法a.foo(b);System.out.println("进入了主线程之后");}public void run() {Thread.currentThread().setName("副线程");// 调用b对象的bar方法b.bar(a);System.out.println("进入了副线程之后");}public static void main(String[] args) {DeadLock dl = new DeadLock();new Thread(dl).start();dl.init();}}
解决办法
- 专门的算法、原则
- 尽量减少同步资源的定义
- 尽量避免嵌套同步
解决线程安全问题的方式三:Lock锁 —- JDK5.0新增
- 从JDK5.0开始,Java提供了更强大的线程同步机制————通过显示定义同步锁对象来实现同步。同步锁使用Lock对象充当。
- java.until.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对LOck对象加锁,线程开始访问共享资源之前应先获得Lock对象。
- ReentrantLock 类实现了Lock,它拥有与synchronized 相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁、释放锁。
class A{private final ReentrantLock lock = new ReenTrantLock();public void m(){lock.lock();try{//保证线程安全的代码;}finally{lock.unlock();}}}注意:如果同步代码有异常,要将unlock()写入finally语句块
/**** 解决线程安全问题的方式三:Lock锁 --- JDK5.0新增*/class Window implements Runnable{public static int ticket=100;//创建锁对象private ReentrantLock lock=new ReentrantLock();@Overridepublic void run() {while (true){try{//2、调用锁定的方法:lock()lock.lock();if(ticket>0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "卖票:票号" + ticket);ticket--;}else{break;}}finally {//3、调用解锁方法:unlock()lock.unlock();}}}}public class LockTest {public static void main(String[] args) {Window window=new Window();Thread threa1 = new Thread(window);Thread thread2 = new Thread(window);Thread thread3 = new Thread(window);threa1.setName("窗口1");thread2.setName("窗口2");thread3.setName("窗口3");threa1.start();thread2.start();thread3.start();}}
Synchronized 与 Lock 的不同之处
- Lock是显示锁(手动开启和关闭锁,别忘记关闭锁),Synchronized是隐式锁,出了作用域自动释放。
- Lock只有代码块锁,synchronized有代码块锁和方法锁。
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
优先使用顺序
Lock->同步代码块->同步方法
课后习题
/*** 银行有一个账户* 有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额* @author tongfangping* @create 2020-11-07 14:43*/class Account{private double balance;public Account(double balance) {this.balance = balance;}//存钱public synchronized void deposit(double amt){if(amt > 0){balance+=amt;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"存了"+amt+",余额为"+balance);}}}class Customer extends Thread{private Account acc;public Customer(Account acc) {this.acc = acc;}@Overridepublic void run() {for(int i=0;i<3;i++){acc.deposit(1000);}}}public class AccountTest {public static void main(String[] args) {Account account=new Account(0);Customer customer1=new Customer(account);Customer customer2=new Customer(account);customer1.setName("张三");customer2.setName("李四");customer1.start();customer2.start();}}
