当需要资源共享的时候使用同步
同步有两种方法
1.synchronized的代码块
语法:synchronized(对象){}
2.synchronized的方法
synchronized void 方法名(){}
以下是实例
class ThreadDemo020 implements Runnable{
private int ticket=5;
public void run(){
for(int i=5;i>0;i--){
/* synchronized (this){
if(ticket>0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("车票" + ticket--);
}
}*/
tell();
}
}
public synchronized void tell(){
if(ticket>0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("车票" + ticket--);
}
}
}
public class TreadDemo02 {
public static void main(String args[]){
ThreadDemo020 m=new ThreadDemo020();
Thread t1=new Thread(m);
Thread t2=new Thread(m);
Thread t3=new Thread(m);
t1.start();
t2.start();
t3.start();
}
}
运行结果
网友评论