用多线程实现电影院三个窗口买票机制
①同步代码块方式实现
public class MyThread extends Thread{static int sum=0;//static Object object=new Object();@Overridepublic void run() {while(true){//同步代码块synchronized (MyThread.class){if(sum<100){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}sum++;System.out.println(getName()+"正在售卖第"+sum+"张票");}else {break;}}}}
}//测试代码
MyThread myThread1=new MyThread();MyThread myThread2=new MyThread();MyThread myThread3=new MyThread();myThread1.setName("窗口1:");myThread2.setName("窗口2:");myThread3.setName("窗口3:");myThread1.start();myThread2.start();myThread3.start();
②同步方法
public class Myrun implements Runnable{int tacked=0;@Overridepublic void run() {while (true){if (maipiao()) break;}}private synchronized boolean maipiao() {if(tacked==100){return true;}else {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}tacked++;System.out.println(Thread.currentThread().getName()+"正在售卖第"+tacked+"张电影票");}return false;}
}//测试代码
Myrun myrun1=new Myrun();Thread s1=new Thread(myrun1);Thread s2=new Thread(myrun1);Thread s3=new Thread(myrun1);s1.setName("窗口1:");s2.setName("窗口2:");s3.setName("窗口3:");s1.start();s2.start();s3.start();