zoukankan      html  css  js  c++  java
  • 线程同步处理

    class MyThread implements Runnable{
        
        //多个线程访问同一资源时,必须要考虑同步
        //synchronized实现同步,当一个线程调用这个方法时,其他的线程是无法调用的
        //线程同步(安全,但性能不高);不加synchronized是异步(不安全,但性能高)
        //如果有太多同步操作,可能会产生死锁
        int ticket = 100;
        @Override
        public  void run() {
            for(int i=0;i<100;i++) {
                synchronized(this) {//synchronized定义在代码块上
                    if(ticket>0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+"卖了一张, 还剩: "+(--ticket));
                    }
                }
                
    //            this.sale();
            }
    
        }
        //或者把synchronized定义在方法上,实现线程同步
        public synchronized void sale() {
            if(ticket>0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"卖了一张, 还剩:"+--ticket);
            }
        }
        
    }
    public class Demo {
        public static void main(String[] args) {
            MyThread run = new MyThread();
            Thread thread1 = new Thread(run,"A");
            Thread thread2 = new Thread(run,"B");
            Thread thread3 = new Thread(run,"C");
            thread1.start();
            thread2.start();
            thread3.start();
            
        }
    }
  • 相关阅读:
    每日总结2.26
    《梦断代码》阅读笔记三
    每日总结2.25
    每日总结2.24
    每日总结2.23
    每日总结2.22
    每日总结2.19
    《梦断代码》阅读笔记二
    Java-11 形参和实参
    Java-10 final用法
  • 原文地址:https://www.cnblogs.com/wwzyy/p/5533603.html
Copyright © 2011-2022 走看看