java -8多线程同步锁

同步代码块的锁对象是任意对象:(Object obj ; Demo d;)这些都行

同步方法:

把同步关键字synchronized添加到方法上,那么,同步方法的锁对象是

this

同步方法是静态方法,那么这个静态同步方法的锁对象是

类的字节码文件对象

public class SellTicket implements Runnable {
    // 定义100张票
    private int ticket = 100;
    
    //定义同一把锁
    private Object obj = new Object();
    
	   @Override
		public void run() {
			while (true) {
				synchronized (obj) {
					if (tickets > 0) {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()
								+ "正在出售第" + (tickets--) + "张票 ");
					}
				}
			}
		}
		 private synchronized void sellTicket() {
				if (tickets > 0) {
				try {
						Thread.sleep(100);
				} catch (InterruptedException e) {
						e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()
							+ "正在出售第" + (tickets--) + "张票 ");
				}
		}
    	private static synchronized void sellTicket() {
			if (tickets > 0) {
				try {
						Thread.sleep(100);
				} catch (InterruptedException e) {
						e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()
							+ "正在出售第" + (tickets--) + "张票 ");
			}
		}
		@Override
		public void run() {
			while (true) {
				synchronized (SellTicket.class) {
					if (tickets > 0) {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()
								+ "正在出售第" + (tickets--) + "张票 ");
					}
				}
				x++;
			}
		}
 }
    ```

你可能感兴趣的:(Java)