同步方法,仍然后有线程锁.
1 对于非静态方法,线程锁(同步监视器)是this
2 对于静态方法,线程锁是该类.
package com.LearnJava.Thread; /* 同步代码块 synchronized(同步监视器){ //需要同步的代码 } 同步监视器:俗称 锁,可以是任何实例化的类.但是需要共用同一个实例. */ class WindowSell implements Runnable{ Object obj = new Object(); private int ticket = 100; @Override public void run() { while (true) { if(!sellTicket()) break; } } private synchronized boolean sellTicket(){ if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "sell " + ticket--); return true; }else{ return false; } } } public class ThreadTestTicket { public static void main(String[] args) { WindowSell win = new WindowSell(); Thread t1 = new Thread(win); t1.setName("1号窗口"); Thread t2 = new Thread(win); t2.setName("2号窗口"); Thread t3 = new Thread(win); t3.setName("3号窗口"); t1.start(); t2.start(); t3.start(); } }
原文地址:https://www.cnblogs.com/superxuezhazha/p/12283506.html
时间: 2024-11-08 20:27:29