关于卖票的问题: 100张票有4个窗口去卖票(4个线程去执行),使用synchronzed实现线程的同步。 synchronized (Ticket.class) 这里的锁对象不要用this去加锁,因为在主函数中创建了4个不同的线程。
package 卖票问题;
public class demo1_thread {
/*
四个窗口去卖100张票
*/
public static void main(String[] args) {
//创建4个线程
new Ticket().start();
new Ticket().start();
new Ticket().start();
new Ticket().start();
}
}
class Ticket extends Thread {
static int ticket = 100;//用static 修饰的变量是 全局变量
@Override
public void run() {
while (true) {
//为了让4个线程同步 synchronized关键字
synchronized (Ticket.class) { //this代表的是当前的对象 在主函数中创建了4个对象 所以任然不能实现同步
if (ticket == 0) {
break;
} else {
try {
//睡眠一下在卖
sleep(10); //当ticket=1 Thread1睡 Thread2 Thread3 ,Thread4都进了 都在睡眠
//Thread1醒 ticket--=0,Thread2醒 ticket--=-1 所以就不断产生了复数
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + "这是第" + ticket-- + "张票");
}
}
}
}
}