package com.yt.hzh; /* * 售票 * */ public class Ticket { private int num = 100; // int a = 0; /* * 同步锁,保证线程同步,作用在方法上面,此方法同一时刻只允许一个线程执行 * 同步方法 * */ public synchronized void sale(){ if (num>0){ System.out.println(Thread.currentThread().getName()+"卖出了第"+num+"张票"); num--; } // a++; // System.out.println("一共卖出的票:"+a); } public void sale2(){ /* * 同步代码块,给一段代码上锁,锁可以是任何对象,但是必须是多个线程共同拥有的对象 * 即多个线程拥有的是同一把锁,这样才可以起到互斥作用 * this当前对象锁,也可以用类.class * 代码块同时只能被一个线程执行 * */ if (num>0){ synchronized (this){ System.out.println(Thread.currentThread().getName()+"卖出了第"+num+"张票"); num--; } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
new线程出来卖票
方法一:
Thread t1 =new Thread(){
@Override
public void run() {
Ticket ticket = new Ticket();
ticket.sale();
}
};
方法二:
Runnable r1 = new Runnable(){
//匿名内部类
@Override
public void run() {
for(int i =0;i<10;i++){
ticket.sale2();
}
}
};
Thread t1 = new Thread(r1,"窗口1");
t1.start();
方法二可以变成这样:
new Thread(()->{ for (int i=0;i<10;i++){ //这里只卖了10张票 ticket.sale2(); } }).start();