Java 多线程初探索之模拟车站多窗口售票

来源:互联网 发布:算法求最小公倍数 编辑:程序博客网 时间:2024/04/28 02:27

欢迎各路大神批评指正

---------------------------------->分割线<---------------------------------

阅读之前,你应该了解:

1.java多线程的两种写法

2.线程变量

3.Java线程工作内存与主内存变量交换过程


思考:模拟一个车站多窗口售票程序,必须满足以下条件:(1)必须多个窗口进行售票(2)票不可多卖,比如有20张票,不能卖出21张

开始写一个售票程序:

public class Test {    public static void main(String[] args) {        for(int i = 1;i <= 10;i++){            new Thread(new MyThread("窗口"+i)).start();            System.out.println("线程"+i+"启动了");        }    }}class MyThread implements Runnable{    private String name;//当前售票窗口编号    private static final int total = 20;//总票数    public MyThread(String name) {        super();        this.name = name;    }    public MyThread(){        super();    }    @Override    public synchronized void run() {        for (int i = 1; i <= total; i++) {            System.out.println(this.name + "卖出了票" + current);            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

看起来似乎没什么毛病,执行一下:

这一看就有问题,为什么我用了同步,依旧是出问题了。肯定是同步用的不对,考虑到卖了哪张票应该是所有窗口都需要知道的,比如窗口1卖了编号为1的票,窗口2就应该知道1号票被卖出去了,针对这个问题,我们做一下改进:

public class Test {    public static void main(String[] args) {        for(int i = 1;i <= 10;i++){            new Thread(new MyThread("窗口"+i)).start();            System.out.println("线程"+i+"启动了");        }    }}class MyThread implements Runnable{    private String name;//售票窗口名称    private static final int total = 20;//总票数    private static int current = 1;//当前应该卖的票的编号    public MyThread(String name) {        super();        this.name = name;    }    public MyThread(){        super();    }    @Override    public synchronized void run() {        for (; current <= total; current++) {            System.out.println(this.name + "卖出了票" + current);            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

,执行一下:


我去,还是有问题,这错误到底是在哪??????????

其实这个问题是同步出现了问题,在Test类的main函数中,我们启动的10个线程,每个线程都有一个MyThread类,在执行run方法的时候,每个线程都去获得自己MyThread类的锁,这个只要不出什么其他问题,都会获取到。这样10个线程相互独立,都获取自己线程内的锁,还有锁竞争吗?没有竞争还需要同步吗?很显然,问题出现在了10个线程竞争的不是同一个锁上面了,那么我们来改进这个问题,想办法让线程竞争同一个锁,于是:

public class Test {    public static void main(String[] args) {        for(int i = 1;i <= 10;i++){            new Thread(new MyThread("窗口"+i)).start();            System.out.println("线程"+i+"启动了");        }    }}class MyThread implements Runnable{    private String name;//售票窗口名称    private static final int total = 20;//总票数    private static int current = 1;//当前应该卖的票的编号    public static final String lock = "我是锁";//静态类,让线程竞争这个类的锁    //因为在内存中,MyThread.lock只有一个,所以竞争这个类的锁    public MyThread(String name) {        super();        this.name = name;    }    public MyThread(){        super();    }    @Override    public void run() {        while (current <= total) {            synchronized (MyThread.lock) {//1.售票的过程是原子的,不可分割的,                                          //2.多个线程会MyThread.lock这个类的锁,这次锁只有一个,会发生竞争                System.out.println(this.name + "卖出了票" + current);                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                current++;            }        }    }}
执行:

这次看起来问题不大,可是:


这就很尴尬了,本来就20张票,愣生生的卖出去29张

鉴于这种卖超的问题,我们加个限制条件应该就可以了:

public class Test {    public static void main(String[] args) {        for(int i = 1;i <= 10;i++){            new Thread(new MyThread("窗口"+i)).start();            System.out.println("线程"+i+"启动了");        }    }}class MyThread implements Runnable{    private String name;//售票窗口名称    private static final int total = 20;//总票数    private static int current = 1;//当前应该卖的票的编号    public static final String lock = "我是锁";//静态类,让线程竞争这个类的锁    //因为在内存中,MyThread.lock只有一个,所以竞争这个类的锁    public MyThread(String name) {        super();        this.name = name;    }    public MyThread(){        super();    }    @Override    public void run() {        while (current <= total) {            synchronized (MyThread.lock) {//1.售票的过程是原子的,不可分割的,                                          //2.多个线程会MyThread.lock这个类的锁,这次锁只有一个,会发生竞争                if(current > total){                    System.out.println("票卖完了");                    break;                }                System.out.println(this.name + "卖出了票" + current);                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                current++;            }        }    }}

执行:


看起来应该没啥问题了。思考下:刚才为什么会卖超?,我输出了一下卖超情况的票的编号,代码如下:

public class Test {    public static void main(String[] args) {        for(int i = 1;i <= 10;i++){            new Thread(new MyThread("窗口"+i)).start();            System.out.println("线程"+i+"启动了");        }    }}class MyThread implements Runnable{    private String name;//售票窗口名称    private static final int total = 20;//总票数    private static int current = 1;//当前应该卖的票的编号    public static final String lock = "我是锁";//静态类,让线程竞争这个类的锁    //因为在内存中,MyThread.lock只有一个,所以竞争这个类的锁    public MyThread(String name) {        super();        this.name = name;    }    public MyThread(){        super();    }    @Override    public void run() {        while (current <= total) {            synchronized (MyThread.lock) {//1.售票的过程是原子的,不可分割的,                                          //2.多个线程会MyThread.lock这个类的锁,这次锁只有一个,会发生竞争                if(current > total){                    System.out.println("票卖完了,当前票的编号为:"+current);                    //break;                }                System.out.println(this.name + "卖出了票" + current);                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                current++;            }        }    }}

执行:

很明显,除了卖出票20的那个窗口(线程),后面每个窗口(线程)都多卖票了,而且每个多卖一张。这是为什么?

猜想:

线程在执行到

这个地方的时候,current变量为线程私有变量,假设线程1执行到这里,它的线程内变量current(这个线程内的current是从内存中拷贝过来的)是20,符合条件,而另外一个线程,我们认为这个线程是线程2,它的变量current是19,因为线程1拿到了锁,线程2被阻塞,希望拿到锁。线程1继续执行,卖完票20之后,把current++,变为21并且释放锁的时候把current同步到内存,此时内存的current为21。线程2拿到了锁,开始执行卖票,因为current被线程1改成了21,所以,线程2 把票21卖出了,此时票卖超了。综上所述,线程实在while(current <= total)后开始竞争锁,因为判断的时候这个while(current <= total)是成立的,所以会执行进while的范围内,而在竞争锁的时候,其他窗口(线程)已经

把票卖完,而当前线程已经执行进了while,不会再判断,于是,票卖超了,我们加上if(current > total)这个判断,就是去掉在等待锁的过程中,其他窗口(线程)把票卖完的情况。

如有不妥之处,欢迎批评指正。