zoukankan      html  css  js  c++  java
  • Java之同步方法处理继承Thread类的线程安全问题



    /**
    * 使用同步方法处理继承Thread类的方式中的线程安全问题
    *
    */
    class Window4 extends Thread {


    private static int ticket = 100;

    @Override
    public void run() {

    while (true) {

    show();
    }

    }
    private static synchronized void show(){//同步监视器:Window4.class
    //private synchronized void show(){ //同步监视器:t1,t2,t3。此种解决方式是错误的
    if (ticket > 0) {

    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
    ticket--;
    }
    }
    }


    public class WindowTest4 {
    public static void main(String[] args) {
    Window4 t1 = new Window4();
    Window4 t2 = new Window4();
    Window4 t3 = new Window4();


    t1.setName("窗口1");
    t2.setName("窗口2");
    t3.setName("窗口3");

    t1.start();
    t2.start();
    t3.start();

    }
    }
  • 相关阅读:
    memset使用技巧
    04.碰撞反应
    03.键盘状态跟踪与精灵删除
    02.基本动作
    01.基本图形
    00.入门
    03.交互--鼠标,键盘
    02.action--新增精灵知识点
    01.helloworld--标签
    05.声音
  • 原文地址:https://www.cnblogs.com/wpy188/p/12099888.html
Copyright © 2011-2022 走看看