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

    在静态方法上面加synchonizd用的是字节码文件锁

    package com.cppdy;
    
    class MyThread8 implements Runnable {
    
        private static Integer ticketCount = 100;
        public boolean falg = true;
    
        @Override
        public void run() {
            if (falg) {
                synchronized (MyThread8.class) {
                    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 static 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 ThreadDemo8 {
    
        public static void main(String[] args) throws Exception {
            MyThread8 mt = new MyThread8();
            Thread thread1 = new Thread(mt, "窗口1");
            Thread thread2 = new Thread(mt, "窗口2");
            thread1.start();
            Thread.sleep(30);
            mt.falg = false;
            thread2.start();
        }
    
    }

    一般情况下,不使用static锁:JVM编译的时候,static是存到方法区,方法区是垃圾回收机制不会回收的

  • 相关阅读:
    4.一对多关联映射
    3.一对一关联映射
    1.Hibernate框架
    19。数据库技术及分页
    18.文件的上传和下载
    17.JavaMail
    16.部署描述符文件
    15.Servlet程序结构与部署
    dba-查询sql耗时
    (72)C# 特性
  • 原文地址:https://www.cnblogs.com/jiefu/p/10015735.html
Copyright © 2011-2022 走看看