您好,欢迎来到要发发知识网。
搜索
您的当前位置:首页Java 同步代码块

Java 同步代码块

来源:要发发知识网

public class ThreadDemo5 {

 public static void main(String[] args) {
  //开启四个线程 实现资源共享的目的
TestThread4 testThread4 = new TestThread4();
Thread thread = new Thread(testThread4);
thread.start();
//资源数据访问不同步
new Thread(testThread4).start();
new Thread(testThread4).start();
new Thread(testThread4).start();

   }

}
class TestThread4 implements Runnable{

private int tickets = 20;
@Override
public void run() {
    // TODO Auto-generated method stub
    //在同一个时间片刻 只能有一个线程来访问这块共享资源
    //只有当访问中的线程离开了,下一个线程才能够访问这块共享资源
    synchronized (this) {//同步线程锁
        while (true) {//进入死循环
            if (tickets > 0) {
                 try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                 System.out.println(Thread.currentThread().getName() + "出票号:"+tickets -- );
            }
        }
    }
    
}

}

Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务