代码如下:
实现类:
package com.java.day18; // 线程安全 public class ThreadSafe implements Runnable{ // 票的数量 private int ticket = 100; // 创建锁对象 Object obj = new Object(); // 设置线程任务,卖票 @Override public void run() { while (true){ // 锁对象的作用,把代码锁住,只让一个线程在同步代码块中执行 synchronized (obj){ if (ticket > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"-->正在卖第"+ticket+"张票"); ticket--; } } } } }
测试类:
package com.java.day18; // 模拟卖票 public class TestThreadSafe { public static void main(String[] args) { ThreadSafe tf = new ThreadSafe(); Thread td1 = new Thread(tf); Thread td2 = new Thread(tf); Thread td3 = new Thread(tf); td1.start(); td2.start(); td3.start(); } }
运行结果:
同步技术原理: