线程安全概念:当多个线程访问同一个类时,这个类始终能保持正确的行为,那么这个类(对象或方法)就是线程安全的。
synchronized:可以在任意对象或方法上加锁,加锁的这段代码被称为“互斥区”或“临界区”。
package com.daniu56.thread;
@SuppressWarnings("unused")
public class Thread01 extends Thread{
private int count = 0;
public void run(){
count++;
System.out.println(this.currentThread().getName() +"===="+ count);
}
public static void main(String[] args) {
Thread01 myThread = new Thread01();
Thread thread01=new Thread(myThread,"t1");
Thread thread02=new Thread(myThread,"t2");
Thread thread03=new Thread(myThread,"t3");
Thread thread04=new Thread(myThread,"t4");
Thread thread05=new Thread(myThread,"t5");
thread01.start();
thread02.start();
thread03.start();
thread04.start();
thread05.start();
}
}
没有加“synchronized”之前,运行结果如下
t1====1
t2====3
t3====3
t4====3
t5====5
加入之后
变为
t1====1
t2====2
t3====3
t4====4
t5====5