解决线程安全问题实现2
(2)同步方法
同步方法是指进入该方法时需要获取this 对象的同步锁, 在方法上使用
synchronized 关键字,
使用this 对象作为锁,也就是使用了当前对象,因为锁住了方法,所以相对于代
码块来说效率相对较低。
注:静态同步方法的锁是该方法所在的类的字节码文件对象,即类名.class 文件
格式:修饰词synchronized 返回值类型方法名(参数列表){
需同步的代码;
}
如果锁对象是this,就可以考虑使用同步方法。
否则能使用同步代码块的尽量使用同步代码块。
package java.thread;
/**
*同步方法
*/
public class ThreadDemo5 {
public static void main(String[] args) {
TicketPool pool = new TicketPool();
Saler2 s1 = new Saler2("s1",pool);
Saler2 s2 = new Saler2("s2",pool);
s1.start();
s2.start();
}
}
/**
* 票池
*/
class TicketPool{
//总票数
private int tickets = 100 ;
//取票,当前对象为锁
public synchronized int getTick(){
int temp = tickets ;
tickets -- ;
if(temp <= 0 ){
return 0 ;
}
return temp ;
}
}
/**
* 售票员
*/
class Saler2 extends Thread {
//总票数
private static int tickets = 100;
private String name0;
//票池
private TicketPool pool ;
private int sleep;
public Saler2(String name0, TicketPool pool) {
this.name0 = name0;
this.pool = pool ;
}
public String getName0() {
return name0;
}
public void setName0(String name0) {
this.name0 = name0;
}
public void run() {
while(true){
int tick = pool.getTick();
if (tick == 0){
return ;
}
System.out.println(name0 + " : " + tick);
Thread.yield();
}
}
}