现在的位置: 首页 > 综合 > 正文

JAVA的线程同步

2018年04月16日 ⁄ 综合 ⁄ 共 486字 ⁄ 字号 评论关闭

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

}

}

 

抱歉!评论已关闭.