在JAVA中提供了同步机制,可以有效地防止资源冲突,同步机制使用synchronized关键字
pubic class CopyOfThreadSafeTest implements Runnable{
int num=10;
public void run(){
while(true){
synchronized(""){
if (num>0){
try{
Thread.slepp(1000);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("tickets""+--num);
}
}
}
}
public static void main(String[] args){
CopyOfThreadSafeTest t=new CopyOfThreadSafeTest ();
Thread tA=new Thread(t);
Thread tB=new Thread(t);
Thread tC=new Thread(t);
Thread tD=new Thread(t);
tA.start();
tB.start();
tC.start();
tD.start();
}
}
本文通过一个具体的示例展示了Java中如何使用synchronized关键字来实现线程安全,避免多个线程同时修改同一份资源导致的问题。
451

被折叠的 条评论
为什么被折叠?



