
1、为了保持跨线程的正确可见性,必须使用synchronized或volatile。
2、读取可能是另一个线程最终写入的变量。
3、写一个可能被另一个线程读取的变量。
实例
classSellTicketimplementsRunnable{
privateinttickets=10;
publicvoidrun(){
while(true){
if(tickets>0)
sell();
else
return;
}
}
publicsynchronizedvoidsell(){
if(tickets>0){
System.out.println(Thread.currentThread().getName()+"卖出第"+tickets+"张票");
tickets--;
try{
Thread.sleep(500);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
publicclassTicketTest{
publicstaticvoidmain(Stringargs[]){
SellTickett=newSellTicket();
newThread(t,"窗口1").start();
newThread(t,"窗口2").start();
newThread(t,"窗口3").start();
System.out.println("主线程结束");
}
}
以上就是java同步的使用条件,希望对大家有所帮助。更多Java学习指路:Java基础
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容