java空中网面试题2.

题目:


package queue;
	
	public class Test2 {
	
		public static void main(String[] args) {
			
			System.out.println("begin:"+(System.currentTimeMillis()/1000));
			for(int i=0;i<10;i++){  //这行不能改动
				String input = i+"";  //这行不能改动
				String output = TestDo.doSome(input);
				System.out.println(Thread.currentThread().getName()+ ":" + output);
			}
		}
	}
	
	//不能改动此TestDo类
	class TestDo {
		public static String doSome(String input){
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String output = input + ":"+ (System.currentTimeMillis() / 1000);
			return output;
		}
	}



代码:

package Exce;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;


	public class Test2 { //只能使用阻塞队列了
	    static BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
		public static void main(String[] args) {
			System.out.println("begin:"+(System.currentTimeMillis()/1000));
			//给你一盏灯
			final Semaphore semaphore = new Semaphore(1);
			for(int j=0;j<10;j++){
				new Thread(new Runnable(){
					@Override
					public void run() {
						try {
							//一盏灯所以一个时刻只允许一个线程去执行
							semaphore.acquire();
							String input = queue.take();
							String output = TestDo.doSome(input);
							System.out.println(Thread.currentThread().getName()+ ":" + output);
							semaphore.release();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}	
					}
				}).start();
			}
		    for(int i=0;i<10;i++){  //这行不能改动
			String input = i+"";  //这行不能改动
			try {
				queue.put(input);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				} 
			}	
		}
	
	
	//不能改动此TestDo类
	class TestDo {
		public static String doSome(String input){
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String output = input + ":"+ (System.currentTimeMillis() / 1000);
			return output;
		}
	}


你可能感兴趣的:(java空中网面试题2.)