关于线程中synchronized的用法之一锁引用

xiaoxiao2021-02-28  73

public class SynDemo1 extends Thread { public static void main(String[] args) { Web12306 web = new Web12306(); Thread a1 = new Thread(web, "a"); Thread a2 = new Thread(web, "b"); Thread a3 = new Thread(web, "c"); a1.start(); a2.start(); a3.start(); } } class Web12306 implements Runnable { private int i = 10; public void run() { try { add(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void add() throws InterruptedException { while (i > 0) { synchronized (Web12306.class) { if (i <= 0) { break; } else { System.out.println(Thread.currentThread().getName() + ":" + i--); Thread.sleep(1000); } } } } }
转载请注明原文地址: https://www.6miu.com/read-56605.html

最新回复(0)