320同步技术原理和321解决线程问题同步方法

.同步技术原理

 

 

解决线程安全问题的一种方案:使用同步代码块格式:

  synchronized(锁对象){

    可能会出现线程安全问题的代码(访问了共享数据的代码)

  }

注意:

  1.通过代码块中的锁对象,可以使用任意的对象

  2.但是必须保证多个线程使用的锁对象是同一个

  3.锁对象作用:

 

    把同步代码块锁住,只让一个线程在同步代码块中执行

 
public class RunnableImpl implements Runnable{

    Object obj = new Object();

    private int ticket = 100;
    //设置线程任务:卖票

    @Override
    public void run() {
        //使用死循环,让卖票操作重复执行while(true){
        //先判断票是否存在
        while (true){
            synchronized (obj){
                payTicket();
            }
        }

    }
    public synchronized void  payTicket(){
        if(ticket>0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //票存在,卖票ticket--
            System.out .println(Thread.currentThread( ).getName()+"-->正在卖第" +ticket+"张票"+ticket--);
        }
    }
}
 
 
public static void main(String[] args) {
        RunnableImpl runnable = new RunnableImpl();
        Thread thread = new Thread(runnable);
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);

        thread.start();
        thread1.start();
        thread2.start();
    }
 
posted @ 2022-07-08 11:08  ja不会va  阅读(24)  评论(0)    收藏  举报