多线程synchronized、wait与notify

例一:烧水和洗盘子

public class A {
	public static void main(String[] args) throws InterruptedException {
		Object object = 2;//烧到2水睡眠
		
		HeatWater heatWater=new HeatWater(object);
		Thread thread=new Thread(heatWater);
		
		DishWashing dishWashing=new DishWashing(object);
		Thread thread2=new Thread(dishWashing);
		
		thread.start();
		Thread.sleep(1000);//确保先进行thread线程
		thread2.start();
	}
}

public class HeatWater implements Runnable{
	Object object;
	public HeatWater(Object object) {
		this.object = object;
	}
	
	@Override
	public void run() {
			synchronized (object) {
				for (int i = 1; i < 5; i++) {
					System.out.println("烧"+i+"水");
					try {
						Thread.sleep(1500);
						if(i==Integer.parseInt(object.toString())){
							object.wait();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
}


public class DishWashing implements Runnable{
	Object object;
	public DishWashing(Object object) {
		this.object = object;
	}
	
	@Override
	public  void run() {
		synchronized (object) {
			for (int i = 1; i < 5; i++) {
				System.out.println("开始洗"+i+"盘子");
				try {
					Thread.sleep(1500);	
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			object.notify();
		}
	}
}

输出结果:
烧1水
烧2水
开始洗1盘子
开始洗2盘子
开始洗3盘子
开始洗4盘子
烧3水
烧4水

例二:抢票

public class A {
	public static void main(String[] args) {
		BuyTicket buyTicket = new BuyTicket();

		Thread t = new Thread(buyTicket, "红红");
		Thread t1 = new Thread(buyTicket, "翠花");
		
		t.start();
		t1.start();

	}
}

public class BuyTicket  implements Runnable {

	// 票数
	int a = 100;

	public void run() {
		// 循环取票
		for (int i = 0; i <= 100; i++) {
			// 同步锁
			synchronized (this) {
				// 判断票数
				if (a > 0) {
					// 每取一次票的时候让票数-1
					a--;
					System.out.println(Thread.currentThread().getName() + "开始买票..");
					System.out.println(Thread.currentThread().getName() + "买票结束剩余.." + a + "张票");
					try {
						 Thread.sleep(200);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}
输出结果:
红红开始买票..
红红买票结束剩余..99张票
红红开始买票..
红红买票结束剩余..98张票
翠花开始买票..
翠花买票结束剩余..97张票
红红开始买票..
红红买票结束剩余..96张票
翠花开始买票..
翠花买票结束剩余..95张票
。。。。。



你可能感兴趣的:(Java)