zoukankan      html  css  js  c++  java
  • java多线程快速入门(十一)

    在方法上面加synchonizd用的是this锁

    package com.cppdy;
    
    class MyThread7 implements Runnable {
    
        private Integer ticketCount = 100;
        public boolean falg = true;
    
        @Override
        public void run() {
            if (falg) {
                synchronized (this) {
                    while (ticketCount > 0) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。");
                        ticketCount--;
                    }
                }
            } else {
                while (ticketCount > 0) {
                    sale();
                }
            }
        }
    
        public synchronized void sale() {
            if (ticketCount > 0) {
                try {
                    Thread.sleep(50);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。");
                ticketCount--;
            }
        }
    }
    
    public class ThreadDemo7 {
    
        public static void main(String[] args) throws Exception {
            MyThread7 mt = new MyThread7();
            Thread thread1 = new Thread(mt, "窗口1");
            Thread thread2 = new Thread(mt, "窗口2");
            thread1.start();
            Thread.sleep(30);
            mt.falg = false;
            thread2.start();
        }
    
    }

  • 相关阅读:
    数字精确运算BigDecimal经常用法
    C3P0数据库连接池使用
    Theano学习笔记(四)——导数
    Leetcode--Merge Intervals
    1191 数轴染色
    P1021 邮票面值设计
    P1032 字串变换
    P1294 高手去散步
    P1832 A+B Problem(再升级)
    P1332 血色先锋队
  • 原文地址:https://www.cnblogs.com/jiefu/p/10015666.html
Copyright © 2011-2022 走看看