------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
同步函数用的是哪一个锁呢?
同步函数需要被对象调用,那么函数都有一个所属对象的引用.就是this
所以同步函数使用的锁就是this.
通过该程序进行验证.
使用2个线程来卖票
一个线程在同步代码块中.
一个线程在同步函数中.
都在执行卖票动作
package src.com.itheima;
public class ThreadDemo implements Runnable {
private int tick=100;
Object obj =new Object();
boolean boo=true;
public void run(){
if(boo){
while(true){
synchronized (this) {
if(tick>0){
try{Thread.sleep(10);}catch(Exception e){ }
System.out.println(Thread.currentThread().getName()+"--code---"+tick--);
}
}
}
}else{
while(true)
show();
}
}
public synchronized void show() {
if(tick>0){
try{Thread.sleep(10);}catch(Exception e){ }
System.out.println(Thread.currentThread().getName()+"---show----"+tick--);
}
}
public static void main(String[] args) {
ThreadDemo t=new ThreadDemo();
Thread a=new Thread(t);
Thread b=new Thread(t);
a.start();
t.boo=false;
b.start();
}
}