多线程之线程安全初探

时间:2022-08-30 13:10:28
public class ThreadDemo3 extends Thread{
private int count=5;

public ThreadDemo3(String name) {
super(name);
// TODO Auto-generated constructor stub
}

@Override
public void run() {

super.run();
while(count >0){
count --;
System.out.println("由"+this.currentThread().getName()
+"计算,count="+count);


}
}


}

public static void main(String[] args) {
/*
ThreadDemo demo=new ThreadDemo();
demo.start();
System.out.println("maim !!!!!!!!!!!!!!!");



Runnable runnable=new ThreadDemo2();
Thread thread=new Thread(runnable);
thread.start();
System.out.println("main");
*/

ThreadDemo3 a=new ThreadDemo3("A");
ThreadDemo3 b=new ThreadDemo3("B");
ThreadDemo3 c=new ThreadDemo3("C");
a.start();
b.start();
c.start();
}

多线程之线程安全初探


由此可以看出几个线程都各自对实例变量操作,数据不共享


如果想让几个线程共享数据则需要去掉while循环


public class ThreadDemo3 extends Thread{
private int count=5;

public ThreadDemo3(String name) {
super(name);
// TODO Auto-generated constructor stub
}

@Override
public void run() {

super.run();
count - -;
}


}

结果为


由A计算,count 3

由B计算,count 3

由C计算,count 2



出现了线程不安全的问题


解决方案是需要同步线程,用synnchronized关键字

该关键字可以在任意的对象,方法上枷锁,枷锁之后直到一个线程运行完毕之后另一个线程才获得权限去运行

需要排队