java的线程和唤醒基础练习题
- 要求使用多线程来模拟电影院卖票,有3个窗口同时卖100张同一场的电影票。
分析:可以用3个线程来模拟售票员,可以使用Runnable接口来实现,来看代码:
package Tick;
public class RunnableImpl implements Runnable{
private int ticket=100;
Object object=new Object();
@Override
public void run() {
while(true){
synchronized (object){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+
"正在卖--->"+ticket+"票");
ticket--;
}
}
}
}
}
主方法调用:
package Tick;
public class Ticket_demo {
public static void main(String[] args) {
Runnable r1=new RunnableImpl();
Thread t1=new Thread(r1,"售票员一号");
t1.start();
Thread t2=new Thread(r1,"售票员二号");
t2.start();
Thread t3=new Thread(r1,"售票员三号");
t3.start();
}
}
2.使用线程的唤醒机制来实现线程的通信,来模拟去点菜和等待上菜的过程
分析:我们可以使用Object自带的wait()和notify()来实现通信,如果想实现多个顾客,可以创建多个顾客线程来实现模拟。
package Tick;
public class Wating_Notify {
public static void main(String[] args) {
Object object=new Object();
new Thread(){
@Override
public void run() {
while(true){
synchronized (object){
System.out.println("我需要什么菜");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("顾客开始吃菜");
System.out.println("-------------------");
}
}
}
}.start();
new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object){
System.out.println("菜做好了上菜了");
object.notify();
}
}
}
}.start();
}
}