1.使用synchronized修饰代码块,使用语法如下:
public class Ticket implements Runnable{ /**车票库存*/ int tickets = 100; /**创建一个锁对象,这个对象有多个线程共同使用*/ static Object obj = new Object(); @Override public void run(){ while (true){ //多线程共享代码块 synchronized (obj) { if (tickets > 0) { System.out.println(Thread.currentThread().getName() + "窗口正在售卖第" + (tickets--) + "票"); } else { break; } } } System.out.println(Thread.currentThread().getName()+"窗口售完票"); } }
2.使用synchronized修饰对象方法,代码如下:
public class Ticket implements Runnable{ /**车票库存*/ int tickets = 100; @Override public void run(){ while (true){ if(isFinish()) { break; } } System.out.println(Thread.currentThread().getName()+"窗口售完票"); } public synchronized boolean isFinish(){ boolean isFinish = false; if (tickets > 0) { System.out.println(Thread.currentThread().getName() + "窗口正在售卖第" + (tickets--) + "票"); } else { isFinish = true; } return isFinish; } public static void main(String args[]){ Ticket ticket = new Ticket(); Thread thread1 = new Thread(ticket,"窗口1"); Thread thread2 = new Thread(ticket,"窗口2"); Thread thread3 = new Thread(ticket,"窗口3"); Thread thread4 = new Thread(ticket,"窗口4"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } }
需要注意的是,现在的锁对象为当前this的Ticket。
3.使用synchronized修饰类方法,代码如下:
public class Ticket extends Thread{ private String name; public Ticket(String name){ super(name); this.name = name; } /**车票库存*/ static int tickets = 100; @Override public void run(){ while (true){ if(isFinish()) { break; } } System.out.println(Thread.currentThread().getName()+"窗口售完票"); } public static synchronized boolean isFinish(){ boolean isFinish = false; if (tickets > 0) { System.out.println(Thread.currentThread().getName() + "窗口正在售卖第" + (tickets--) + "票"); } else { isFinish = true; } return isFinish; } public static void main(String args[]){ Ticket ticket1 = new Ticket("窗口1"); Ticket ticket2 = new Ticket("窗口2"); Ticket ticket3 = new Ticket("窗口3"); Ticket ticket4 = new Ticket("窗口4"); ticket1.start(); ticket2.start(); ticket3.start(); ticket4.start(); } }
*注意:synchronized中如果有sleep()方法,cup在休眠时期不会让出资源