同步代码块的锁及同步方法应用和锁的问题

    科技2022-08-21  110

    import cn.itcast_01.MyRunnable; public class 同步代码块的锁及同步方法应用和锁的问题 { public static void main(String[] args) { //创建资源对象 MyRunnable my = new MyRunnable(); //创建三个线程对象 Thread t1 = new Thread(my,"窗口1"); Thread t2 = new Thread(my,"窗口2"); Thread t3 = new Thread(my,"窗口3"); //启动线程 t1.start(); t2.start(); t3.start();//创建资源对象 } }

    同步代码块的锁的定义

    package cn.itcast_02; //同步代码块用obj做锁 //public class MyRunnable implements Runnable { // // //定义100章票 // private static int ticked = 100; // // //创建锁对象 // private Object obj = new Object(); // @Override // public void run() { // while(true) { // synchronized (obj) { // if(ticked>0) { // try { // Thread.sleep(100); // } catch (InterruptedException e) { // e.printStackTrace(); // } // System.out.println(Thread.currentThread().getName()+"正在出售第"+(ticked--)+"票"); // } // // } // // } // // } //} //同步代码块用Dome做锁 //public class MyRunnable implements Runnable { // // //定义100章票 // private static int ticked = 100; // // //创建锁对象 // private Dome dome = new Dome(); // // @Override // public void run() { // while(true) { // synchronized (dome) { // if(ticked>0) { // try { // Thread.sleep(100); // } catch (InterruptedException e) { // e.printStackTrace(); // } // System.out.println(Thread.currentThread().getName()+"正在出售第"+(ticked--)+"票"); // } // // } // // } // // } //} public class MyRunnable implements Runnable { //定义100章票 private static int ticked = 100; //创建锁对象 private Object obj = new Object(); @Override public void run() { while(true) { synchronized (obj) { if(ticked>0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+(ticked--)+"票"); } } } } } class Dome{ }
    Processed: 0.018, SQL: 9