1. 程式人生 > >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是存到方法區,方法區是垃圾回收機制不會回收的