当前位置: 首页>后端>正文

线程并发:购票解决

线程并发:购票解决,第1张
线程并发:购票解决,第2张

/**

*同步方法:public synchronized void method(int args){执行体…}

?*

* synchronized方法控制对(synchronized修饰的方法所在的对象,就是this)“对象”的访问,每个对象对应一把锁,

*每个synchronized方法都必须获得调用该方法的锁才能执行,否则线程会阻塞,synchronized所在方法一旦执行,就独占该锁,

*直到方法执行完才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。

*缺陷:若将一个大的方法声明为synchronized 将会影响效率。需要修改的内容才需要锁,锁的太多,浪费资源。

?*/

public class MyTicker2 {

????public static void main(String[] args) throws InterruptedException {

????????BuyTicker2 ticker = new BuyTicker2();

????????Thread person1Thread = new Thread(ticker, "person1");

????????Thread person2Thread = new Thread(ticker, "person2");

????????Thread person3Thread = new Thread(ticker, "person3");

????????person1Thread.start();

????????person2Thread.start();

????????person3Thread.start();

????}

}

class BuyTicker2 implements Runnable{

//车票

????private int tickerNum = 10;

//停止线程标识

????boolean flag = true;

????@Override

????public void run() {

????????while (flag) {

????????????try {

????????????????buyTicker();

????????????} catch (InterruptedException e) {

????????????????e.printStackTrace();

????????????}

????????}

????}

????private synchronized void buyTicker() throws InterruptedException {

//判断是否还有票

????????if (tickerNum <= 0) {

????????????flag = false;

????????????return;

????????}

//模拟延时

????????Thread.sleep(100);

//买票

System.out.println(Thread.currentThread().getName() + "买到第" + tickerNum -- + "张票");

????}

}


https://www.xamrdz.com/backend/3zw1936761.html

相关文章: