快速理解java多线程重要概念[第1部分]

线程的优先级

  1. 线程的优先级与代码执行顺序是无关的,这意味的代码先执行的线程不一定先被调度
   public class Run {
       public static void main(String[] args){
           for (int i = 0 ;i < 5; i++){
               new Thread(()->{
                   Console.log("thread1 run....");
               }).start();
               new Thead(()->{
                   Console.log("thread2 run....");
               }).start();
           }
       }
   }

在上述程序中,线程1总是比线程2先执行程序,但是打印结果确不一定是线程1先执行~

  1. 优先级是具有随机性的:优先级较高的线程也不一定每一次都是最先执行完(实际上这与CPU调度方案相关)

守护线程

  1. 守护线程实际上就是非守护线程保姆,非守护结束,守护线程退出.如下代码:
public static void main(String[] args) throws Exception{
    System.out.println("主线程");
    Thead thread =  new Thead(()->{
        while(true){
            System.out.println("守护线程工作");
        }
    });
    //声明此线程为守护线程
    thread.setDeamond(true);
    thread.start();
    //主线程持续3秒
    Thead.sleep(3000);
}

由于设置为守护线程,则当主线程结束(持续3s)之后,守护线程也会脱离无限循环而退出

非线程安全与线程安全

  1. 一个类具有状态,主要是由其成员变量决定的
public class State{
    private State state1;
    private State state2;
    .....
}
  1. 若一个类中的成员方法使用的变量都是局部变量(没有使用过类的内部成员变量),那么这个类必定是线程安全的(详细参考深入理解JVM,局部变量是线程私有的)
@ThreadSafe
public class State{
    private State state1;
    private State state2;
    //此方法没有使用到类内部成员变量
    public int method1(int a, int b){
        return a + b;
    }
}
  1. 如果多个线程共同访问同一个对象中的实例变量,则有可能出现非线程安全问题
@ThreadUnSafe
public class State{
    private State state;
    public State(State state){
        this.state = state;
    }
    //此方法如果被多个线程同时进入,则会导致紊乱的状态,呈现出线程不安全的状态,得到非预期结果
    public void changeState(){
        if(state......){
            
        }else{
            ........
        }
    }
}

synchronized加锁

这里我们有几个方法可以将上述代码改造成为一个线程安全的类

  1. 方法加锁,保证对于同一对象的同一方法,每次只能由一个线程进入.从而保证线程安全
@ThreadSafe
//重复代码用....省略
public class State{
    ......
	//给方法声明处加上synchronized进行修饰
	public synchronized void changeState(){
        ......
    }
}
  1. 具体的对象加锁,我们可以知道,其实没有必要对于整个方法加锁,在这个类中,出现非线程安全的唯一原因便是对于其state成员变量的多线程访问
@ThreadSafe
//重复代码用....省略
public class State{
    private State state;
    public State(State state){
        this.state = state;
    }
	//锁住指定对象,这种方式在某些情况下更加了灵活
	public void changeState(){
        synchronized(state){
            ......
        }
    }
}

我们分析这两种锁方式的区别: 首先看如下代码

public class DifferentDemo {
	public static void main(String[] args) {
		Component component = new Component();
		Container container = new Container(component);
		component.method1();
		container.method2();
        
	}
}

class Component {
	// 方法加锁
	public synchronized void method1() {
		try {
			System.out.println("do method1");
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
    
    //普通方法不加锁
    public void method3(){
        System.out.println("do method3");
    }
}

class Container {
	private Component component;

	public Container(Component component) {
		this.component = component;
	}

	public void method2() {
		// 锁住成员变量
		synchronized (component) {
			try {
				System.out.println("do method2");
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
输出:
do method1
do method3
...间隔2秒之后...
do method2

Component类本身有一个方法级别锁,而Container中持有Component对象,并且在方法中加入了对象锁,由于一个对象的锁只能同时被一个线程获得,而方法级锁就相当于synchronized(this),所以两个不同类的方法其实都对同一个对象加锁了(component对象),因此两个方法不能同时执行,后一个方法必须等待前一个方法释放锁.而method3可以和method1同时执行,是因为method3并不需要请求获得对象的锁就能执行(没有同步代码块),因此就算对象的锁被其他线程持有了,但是此方法还是可以照常执行.

  1. 除了上述两种锁方法只是对象级别的,但是对于静态方法,我们可能并不需要new出对象,由此还有一致直接对class进行加锁的方式,我们以双重校验锁的单例模式为例
//单例模式的双重校验锁实现
public class Singleton{
    private static Singleton instance;
    ......
	//给方法声明处加上synchronized进行修饰
	public static Singleton getInstance(){
        if(instance == null){
            //可能有多个线程进入第一重校验,因此还要加锁校验一次
            synchronized(Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

在上述程序中,单例类具有静态工厂,所以不需要对象级锁,只需要使用类级别的锁就可以.

注:在静态方法上加上synchronized其实就相当于类级别代码块锁,锁住的是类

关键:弄清楚锁的是谁,锁被谁持有了,锁何时释放

synchronized锁重入

  1. 关键字synchronized是可重入的锁,当一个线程获得到了对象的锁之后,再次请求同一对象锁是可以再次得到的,这也说明了在一个synchronized方法/块内部调用本类同一对象的synchronized方法/块时,是永远可以得到锁的.
public class ReentrantDemo {
	public static void main(String[] args) throws InterruptedException {
		Demo demo = new Demo();
		new Thread(() -> {
			demo.method1();
		}).start();
	}
}

class Demo {
	public synchronized void method1() {
		System.out.println(Thread.currentThread().getName() + "do method1");
		method2();
	}

	public synchronized void method2() {
		System.out.println(Thread.currentThread().getName() + "do method2");
		method3();
	}

	public synchronized void method3() {
		System.out.println(Thread.currentThread().getName() + "do method3");
	}
}
输出:
Thread-0do method1
Thread-0do method2
Thread-0do method3

由此可见.只要主线程获得对象锁调用了method1,便可以再次获得对象锁依次调用method2,method3,同时,锁重入还可以在父子之间进行:线程获取到子类对象的锁,可以调用父类的同步方法.

  1. 同步不能被继承,子类重载方法必须也加上synchronized声明,代码略

synchronized锁的释放

  1. 线程出现异常,持有的锁会自动释放(synchronized锁)
public class ReleaseDemo {
	public static void main(String[] args) throw Exception {
		Object object = new Object();
		new Thread(() -> {
			synchronized (object) {
				try {
					int[] arr = new int[3];
					// 尝试抛出数组下标越界异常
					for (int i = 0; i <= arr.length; i++) {
						Thread.sleep(1000);
						System.out.println(arr[i]);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		Thread.sleep(100);
		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + "等待锁");
			synchronized (object) {
				System.out.println(Thread.currentThread().getName() + "得到锁");
			}
		}).start();
	}
}
输出结果:
Thread-1等待锁
0
0
0
Thread-1得到锁
Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 3
	at 并发.Practice20.lambda$0(Practice20.java:20)
	at java.lang.Thread.run(Thread.java:748)

示例代码中先启动的线程首先得到了object对象的锁,后启动的线程则必须等待,直到前面持有锁的线程抛出了ArrayIndexOutOfBoundsException异常,自动释放了object变量的锁,才能有机会得到锁并打印输出.


本次主要快速理解了java内置的一些关键概念,之后会进一步地引出更多深层次的概念~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值