zoukankan      html  css  js  c++  java
  • synchronized

     1 package com.cn;
     2 
     3 class Test{
     4     public static void main(String [] args){
     5         TestThread t = new TestThread();
     6         new Thread(t).start();
     7         try {
     8             Thread.sleep(10);
     9         } catch (InterruptedException e) {
    10             e.printStackTrace();
    11         }
    12         t.str="method";
    13         new Thread(t).start();
    14     }
    15 }
    16 
    17 class TestThread implements Runnable {
    18     int tickets = 100;
    19     String str = new String("");
    20     public void run() {
    21         if(str.equals("method")){
    22             while(true){
    23                 synchronized (this) {
    24                     if(tickets>0){
    25                         try {
    26                             Thread.sleep(10);
    27                         } catch (InterruptedException e) {
    28                             e.printStackTrace();
    29                         }
    30                         System.out.println(Thread.currentThread().getName()+" is salling ticket "+tickets--);
    31                     }
    32                 }
    33             }
    34         }else{
    35             while(true){
    36                 sale();
    37             }
    38         }
    39     }
    40     public synchronized void sale(){
    41         if(tickets>0){
    42             try {
    43                 Thread.sleep(10);
    44             } catch (InterruptedException e) {
    45                 e.printStackTrace();
    46             }
    47             System.out.println(Thread.currentThread().getName()+" is salling ticket "+tickets--);
    48         }
    49     }
    50 }

    sale()方法使用的监视器对象是this,所以要实现同步代码块和sale()方法之间的同步,同步代码块检查的同步对象也应该为this

  • 相关阅读:
    17-canvas绘制扇形
    16-canvas绘制圆弧
    15-canvas渐变色
    14-canvas绘制柱状图
    13-绘制矩形的简写方式
    12-es6类的方式封装折线图
    11-canvas绘制折线图
    10-canva绘制数据点
    jenkins 环境部署 (yum安装方式)
    BerkeleyDB安装
  • 原文地址:https://www.cnblogs.com/lzy1991/p/5111420.html
Copyright © 2011-2022 走看看