多线程同步小例子,100张票3个窗口同时销售

公司不能登录,很久不发博客,今天偶然看到多线程,发现自己同步用的不好,简单写个例子用synchronized 关键字的例子,100张票 3个窗口同时销售。另外加锁也可以用Lock 接口的实现类,此处不做拓展,可参考Java核心 基础卷

直接上代码。

 

package com.learning.test;

public class TestMutithread {

	public static void main(String[] args) {
		Ticket ticket = new Ticket();
		ticket.number = 100;
		TicketBll ticketBll = new TicketBll(ticket);
		SellTicketRunnable sellTicketRunnable = new SellTicketRunnable(
				ticketBll);
		new Thread(sellTicketRunnable, "A").start();
		new Thread(sellTicketRunnable, "B").start();
		new Thread(sellTicketRunnable, "C").start();
		new Thread(sellTicketRunnable, "D").start();
	}

}

class Ticket {
	public int number;
}

class TicketBll {
	public Ticket ticket;

	public TicketBll(Ticket ticket) {
		this.ticket = ticket;
	}

	public void sellTicket() {

		while (ticket.number > 0) {
			synchronized (ticket) {

				System.out.println(Thread.currentThread().getName() + " sells "
						+ ticket.number--);
			}

			try {
				Thread.sleep(100l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}

}

class SellTicketRunnable implements Runnable {

	private TicketBll ticketBll;

	public SellTicketRunnable(TicketBll ticketBll) {
		this.ticketBll = ticketBll;

	}

	@Override
	public void run() {
		ticketBll.sellTicket();
	}

}
 

你可能感兴趣的:(多线程,synchronized)