线程同步的具体实现

代码示例:

package aaa;

public class TestTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();

Thread t1 = new Thread(ticket);
Thread t2 = new Thread(ticket);
Thread t3 = new Thread(ticket);

t1.start();
t2.start();
t3.start();
ticket.setTicket(20);
}

}

class Ticket implements Runnable {
private int ticket = 5;

public void run() {

for (int i = 0; i < 100; i++) {
// synchronized (this) {//指定同步监视器
// if(ticket>0) {
//
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+":正在卖出第"+ticket+"张票");
// ticket--;
// }
// }

sale();

}

}
private synchronized void sale() {//无需指定同步监视器,只能是当前对象this
if(ticket>0) {

try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":正在卖出第"+ticket+"张票");
ticket--;
}
}

public int getTicket() {
return ticket;
}

public void setTicket(int ticket) {
this.ticket = ticket;
}
}

猜你喜欢

转载自www.cnblogs.com/LuJunlong/p/12096047.html