java多线程快速入门(十)

synchonizd解决安全性问题

package com.cppdy;

class MyThread6 implements Runnable{

    private Integer ticketCount=100;
    private Object ob=new Object();
    
    @Override
    public void run() {
        while(ticketCount>0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sale();
        }
    }
    
    public void sale() {
        synchronized (ob) {
            if(ticketCount>0) {
                System.out.println(Thread.currentThread().getName()+"卖出了第:"+(100-ticketCount+1)+"张票。");
                ticketCount--;
            }
        }
    }
}

public class ThreadDemo6 {

    public static void main(String[] args) throws Exception{
        MyThread6 mt = new MyThread6();
        Thread thread1 = new Thread(mt,"窗口1");
        Thread thread2 = new Thread(mt,"窗口2");
        thread1.start();
        thread2.start();
    }

}

线程安全问题产生的条件:要有两个线程以上;必须要对同一变量进行操作;必须代码块使用同一把锁

原理:一个拿到锁,其它线程进行等待;释放过后,其它线程才能访问,就是锁的竞争问题,也是死锁产生的条件

posted @ 2018-11-25 14:38  知识追求者  阅读(136)  评论(0编辑  收藏  举报