线程安全的概念

版权声明:本文由哎呀妈呀脑壳疼脑壳疼原创,转载请注明 https://blog.csdn.net/u013983628/article/details/82940192

线程安全的概念

线程安全:当多个线程访问某一个类(对象或方法)时,这个类始终都能表现出正确的行为,那么这个类(对象或方法)就是线程安全的

package com.louis.线程;
public class MyThread extends Thread{
    private int count = 5;
    public void run(){
        count--;
        System.out.println(this.currentThread().getName() + " count=" + count);
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        for (int i = 0;i<100;i++){
            Thread t1 = new Thread(myThread, "t"+i);  //线程名
            t1.start();
        }
    }
}

不加synchronized关键字的结果:
在这里插入图片描述
加synchronized关键后
在这里插入图片描述

小彩蛋

Thread t1 = new Thread(myThread, "t"+i);

使用此方式可以给线程取名,方便打印消息,同时也为了以后分析栈溢出异常。
thread构造方法如下:

 public Thread(Runnable target, String name) {
    
  }

猜你喜欢

转载自blog.csdn.net/u013983628/article/details/82940192