miniチケット販売システムの作成スレッドの3つの方法

6071 ワード

シーン
マルチスレッドプログラミングを学び、miniチケット販売システムを書く
に質問
スレッドの作成方法、切符売り場のシミュレーション方法
じっけん
シミュレーション3つの窓口で10枚の切符を売っています.コードは以下の通りです.
/**
 * Project Name:thinkinginjava
 * File Name:ThreadCallable.java
 * Package Name:com.sourcecode.java.thread
 * Date:2016 2 14   10:25:25
 * Copyright (c) 2016, [email protected] All Rights Reserved.
 *
 */
package com.sourcecode.java.thread;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * ClassName: ThreadCallable <br/>
 * Function: TODO mini      <br/>
 * Reason: TODO             <br/>
 * date: 2016 2 14    10:25:25 <br/>
 *
 * @author Administrator
 * @version 1.0
 * @since JDK 1.6
 */
public class ThreadCallable implements Callable<Object>
{
	/*
	 *    -      
	 */
	public static int NUM_ThREADS = 3;

	/*
	 *    
	 */
	public static int TOTAL_TICKETS = 10;

	/*
	 *    
	 */
	private int ticket;

	/**
	 * Creates a new instance of ThreadCallable.
	 *
	 * @param ticket
	 *               
	 */
	public ThreadCallable(int ticket)
	{
		this.ticket = ticket;
	}

	/**
	 * TODO    -        
	 * 
	 * @see java.util.concurrent.Callable#call()
	 */
	@Override
	public Object call() throws Exception
	{
		Date end = null;
		Date begin = new Date();
		while (true)
		{
			if (ticket > 0)
			{
				System.out.println("[Window " + Thread.currentThread().getId() + "] is sailing tiket " + ticket--);
				Thread.sleep(10);
			} else
			{
				end = new Date();
				break;
			}
		}
		long millisTotal = end.getTime() - begin.getTime();

		return TOTAL_TICKETS + " tikcets sold in " + millisTotal + " miliseconds.";
	}
	
	/**
	 * TODO   .<br/>
	 *
	 * @author Administrator
	 * @param args
	 * @since JDK 1.6
	 */
	public static void main(String[] args)
	{
		//            
		ExecutorService poor = Executors.newFixedThreadPool(NUM_ThREADS);
		
		//       Future(           ,  ) :
		Future<Object> future = poor.submit(new ThreadCallable(TOTAL_TICKETS));
		try
		{
			//  ,  get()        
			System.out.println(future.get().toString());
		} catch (Exception e)
		{
			System.out.println("Sorry,system busy, please try again later!");
		}
		
		//     
		poor.shutdown();
	}
}
/**
 * Project Name:thinkinginjava
 * File Name:ThreadRunnable.java
 * Package Name:com.sourcecode.java.thread
 * Date:2016 2 14   11:11:06
 * Copyright (c) 2016, [email protected] All Rights Reserved.
 *
 */
package com.sourcecode.java.thread;

import java.util.Date;

/**
 * ClassName: ThreadRunnable <br/>
 * Function:   3     10    <br/>
 * Reason:          3          <br/>
 * date: 2016 2 14    11:11:06 <br/>
 *
 * @author Administrator
 * @version 
 * @since JDK 1.6
 */
public class ThreadRunnable
{
	/*
	 *    
	 */
	public static int TOTAL_TICKETS = 10;
	
	public static void main(String[] args)
	{
		/*
		 * extends        :         ( 3    10  )
		 */
//		ThreadExtends sellerExt = new ThreadExtends(TOTAL_TICKETS);
//		Date begin = new Date();
//		sellerExt.start();
//		Date end = new Date();
//		long millisTotal = end.getTime()-begin.getTime();
//		System.out.println(TOTAL_TICKETS + " tikcets sold in " + millisTotal + " miliseconds.");
		
		//            3     30   
//		ThreadExtends sellerExt1 = new ThreadExtends();
//		ThreadExtends sellerExt2 = new ThreadExtends();
//		ThreadExtends sellerExt3 = new ThreadExtends();
//		sellerExt1.start();
//		sellerExt2.start();
//		sellerExt3.start();
		
		/*
		 * implements              (3    10  )
		 */
		ThreadImplt seller = new ThreadImplt(TOTAL_TICKETS);
		Thread window1 = new Thread(seller);
		Thread window2 = new Thread(seller);
		Thread window3 = new Thread(seller);
		
		Date begin2 = new Date();
		window1.start();
		window2.start();
		window3.start();
		Date end2 = new Date();
		long millisTotal2 = end2.getTime()-begin2.getTime();
		System.out.println(TOTAL_TICKETS + " tikcets sold in " + millisTotal2 + " miliseconds.");
	}
}

class ThreadExtends extends Thread
{
	/*
	 *    
	 */
	private int ticket; 
	
	/**
	 * Creates a new instance of ThreadExtends.
	 *
	 * @param ticket
	 */
	
	public ThreadExtends(int ticket)
	{
		this.ticket = ticket;
	}

	/**
	 * 
	 * TODO   -  .
	 * @see java.lang.Thread#run()
	 */
	public void run()
	{
		while (true)
		{
			if (ticket > 0)
			{
				System.out.println("[Window " + Thread.currentThread().getId() + "] is sailing tiket " + ticket--);
				try
				{
					Thread.sleep(10);
				}
				catch (InterruptedException e)
				{
					//    
					throw new RuntimeException(e.toString()+"errorCode");
				}
			} 
			else
			{
				break;
			}
		}
	}
}

class ThreadImplt implements Runnable
{
	/*
	 *    
	 */
	private int ticket; 
	
	/**
	 * Creates a new instance of ThreadImplt.
	 *
	 * @param ticket
	 */
	
	public ThreadImplt(int ticket)
	{
		this.ticket = ticket;
	}

	/**
	 * TODO   -  .
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run()
	{
		while (true)
		{
			if (ticket > 0)
			{
				System.out.println("[Window " + Thread.currentThread().getId() + "] is sailing tiket " + ticket--);
				try
				{
					Thread.sleep(10);
				}
				catch (InterruptedException e)
				{
					//    
					throw new RuntimeException(e.toString()+"errorCode");
				}
			} 
			else
			{
				break;
			}
		}
	}
}

まとめ
JAvaでは、スレッドを作成する方法は2つあります.
一、戻りクラスがなく、Runnableインタフェースを実現することとThreadクラスを継承すること(extends Threadは実際にはRunnbaleインタフェースを実現するクラス-Thread自身がRunnbaleインタフェースを実現することにも属している).
  • 私たちは多くの場合、1つのクラスのサブクラスをマルチスレッドに配置します.この場合、implementで作成するしかありません.java単一継承
  • 同じプログラムコードのスレッドは、同じリソースを処理します.例えば、鉄道の切符販売システムのシミュレーションです.

  • 二、返却クラスがあり、即ちCallableインタフェースを実現する.
    参考文献
    1、3種類のスレッドを実現する方式http://www.cnblogs.com/yezhenhan/archive/2012/01/09/2317636.htmlブロガーに感謝!
    2、張孝祥-Javaマルチスレッドと同時ライブラリの高級応用は張先生に敬意を表します!