1. 程式人生 > >執行緒間共享資料例子--售票/退票

執行緒間共享資料例子--售票/退票


例子程式:
package edu.review;

import java.util.Random;
/**
 * 題目要求:
 *   兩個售票視窗,對某一趟列車票進行操作,一個為售票視窗,一個為退票視窗,每個視窗售/退票100張 
 **/
public class Thread2ThreadDataShare {

	public static void main(String[] args) {
		// 方式1();//兩種方式是等效的
		方式2();

	}
	
	public static void 方式1(){
		final DataShare data1 = new DataShare();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 100; i++) {
					try {
						Thread.sleep(new Random().nextInt(20));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					data1.increment();
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 100; i++) {
					try {
						Thread.sleep(new Random().nextInt(20));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					data1.decrement();
				}
				
			}
		}).start();
	}
	
	public static void 方式2(){
		DataShare data2 = new DataShare();
		IncRunnable incRunnable = new IncRunnable(data2);
		DecRunnable decRunnable = new DecRunnable(data2);
		new Thread(incRunnable).start();
		new Thread(decRunnable).start();
	}
	static class IncRunnable implements Runnable{
		DataShare data = new DataShare();
		public IncRunnable(DataShare data){
			this.data = data;
		}
		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				try {
					Thread.sleep(new Random().nextInt(20));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				data.increment();
			}
		}
	}
	static class DecRunnable implements Runnable{
		DataShare data = new DataShare();
		public DecRunnable(DataShare data){
			this.data = data;
		}
		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				try {
					Thread.sleep(new Random().nextInt(20));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				data.decrement();
			}
		}
	}

}

class DataShare{
	private int ticket = 100;
	public synchronized void increment(){
		ticket++;
		System.out.println(Thread.currentThread().getName()+"退票,當前剩"+ticket+"張票!");
	}
	public synchronized void decrement(){
		ticket--;
		System.out.println(Thread.currentThread().getName()+"售票,當前剩"+ticket+"張票!");
	}
	
}