Thread(線程的創建) 十八

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


/**
 * 線程的創建(常用的3種)
 * 1)extends Thread,2)implements Runnable,3)implements Callable
 * 
 * 
 *說明:學習途徑,網絡和書本
 */
public class CreatThread {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//1)
Thread th=new OneThr();
th.setName("黃牛one");
th.start();
//2)
Runnable real=new TwoThr();//創建真實角色
Thread proxy=new Thread(real,"黃牛two");//創建代理類,如果有新增方法,就不能用接口聲明
proxy.start();
//3) 瞭解
ThreeThr realTask=new ThreeThr();
ExecutorService  ser=Executors.newFixedThreadPool(2);
Future<Integer> result=ser.submit(realTask);
Future<Integer> result1=ser.submit(realTask);
//獲取返回值
System.out.println("沒票了:"+result.get());
System.out.println("沒票了:"+result1.get());

Thread.sleep(1000);
//停止服務
ser.shutdown();
}

}
/**
 * 1)extends Thread
 */
class OneThr extends Thread{
private int tickets=20;
@Override
public void run() {//線程體
while(tickets>0){
System.out.println(Thread.currentThread().getName()+",搶到第:"+(tickets--)+"張票");
}
try {
Thread.sleep(500);   //模擬延時時間
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
/**
* 2)implements Runnable
*   代理模式 :真實角色(TwoThr 實現接口)
*          接口(Ruannable)
*          代理角色(Thread 實現接口+引用正式角色)
*/
class TwoThr implements Runnable{
private int tickets=20;
@Override
public void run() {//線程體
while(tickets>0){
System.out.println(Thread.currentThread().getName()+",搶到第:"+(tickets--)+"張票");
}
try {
Thread.sleep(500);   //模擬延時時間
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 1,創建 實現Callable接口的實現類 +重寫call方法
* 2,藉助調度服務(ExecutorService),獲取Future對象
* ExecutorService  ser=Executors.newFixedThreadPool();
* Future result=ser.submit(實現類對象);
* 3)獲取值 result.get();
* 4)停止服務
* @author Administrator
*
*/
class ThreeThr implements Callable<Integer>{
private int tickets=200;
@Override
public Integer call() throws Exception {
while(tickets>0){
System.out.println(Thread.currentThread().getName()+",搶到第:"+(tickets--)+"張票");
}
Thread.sleep(500);
return tickets;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章