zoukankan      html  css  js  c++  java
  • 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();
        }
    
    }

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

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

  • 相关阅读:
    SpringBoot入门
    Java自定义注解(1)
    git集成idea
    git常用命令
    Shiro授权
    shiro认证
    shiro入门
    SpringMVC文件上传
    SpringMVC入门
    mybatis关联关系映射
  • 原文地址:https://www.cnblogs.com/jiefu/p/10015585.html
Copyright © 2011-2022 走看看