多线程 - 3.实例变量与线程安全

实例变量的不共享

实例变量不共享,就不存在多个线程访问同一个变量的情况

class MyThread extends Thread{
    private int count = 5;
    public MyThread(String name){
        super();
        this.setName(name);
    }

    @Override
    public void run(){
        while(count > 0){
            count --;
            System.out.println(Thread.currentThread().getName() + ":.." + count);
        }
    }
}

public class test0{
    public static void main(String[] args){
        Thread myThread_A = new MyThread("A");
        Thread myThread_B = new MyThread("B");
        Thread myThread_C = new MyThread("C");
        Thread myThread_D = new MyThread("D");
        Thread myThread_E = new MyThread("E");
        myThread_A.start();
        myThread_B.start();
        myThread_C.start();
        myThread_D.start();
        myThread_E.start();
    }
}
实例变量的共享

实例变量共享,就可能会重复删除数据、或未删除数据等情况产生

class MyThread extends Thread{
    private int count = 5;
    @Override
    public void run(){
            count --;
            System.out.println(Thread.currentThread().getName() + ":.." + count);
    }
}

public class test1{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        Thread thread_A = new Thread(myThread,"A");
        Thread thread_B = new Thread(myThread,"B");
        Thread thread_C = new Thread(myThread,"C");
        Thread thread_D = new Thread(myThread,"D");
        Thread thread_E = new Thread(myThread,"E");

        thread_A.start();
        thread_B.start();
        thread_C.start();
        thread_D.start();
        thread_E.start();
    }
}
感受实例变量共享的安全问题
class MyThread extends Thread{
    private int count = 50;
    @Override
    public void run(){
            count --;
            System.out.println(Thread.currentThread().getName() + " :.." + count);
    }
}

public class test2{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        for(int i = 0; i < 30; i++){
            Thread thread = new Thread(myThread, "i+" + i);
            thread.start();
        }
    }
}
初次解决实例变量共享的安全问题

在 run 方法前加入 synchronized 关键字,使多个线程在执行 run 方法时,以排队的方式进行处理。

class MyThread extends Thread{
    private int count = 50;
    @Override
    synchronized public void run(){
            count --;
            System.out.println(Thread.currentThread().getName() + " :.." + count);
    }
}

public class test3{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        for(int i = 0; i < 30; i++){
            Thread thread = new Thread(myThread, "i+" + i);
            thread.start();
        }
    }
}

扩展

  1. Java内存模型中的有序性主要依靠 volatile 和 synchronized 来完成。
  2. synchronized 可以在任意对象及方法上加锁,执行上锁的代码块前先判断是否已经上锁
  3. 效率问题,当前 run() 方法内容较少,直接在方法体上加锁,对运行速度的影响并不明显

猜你喜欢

转载自blog.csdn.net/weixin_43845524/article/details/106796744