JAVA的线程同步

来源:互联网 发布:caffe bene 编辑:程序博客网 时间:2024/05/16 09:48

在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();

}

}