21-空中网挑选实习生的面试题(2)

第二题:

package cn.itcast.demo.thread;

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);
		}
	}
}

// 这个类不能动
class TestDo {
	public static String doSome(String input) {
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String output = input + ":" + (System.currentTimeMillis()/1000);
		return output;
	}
}
begin:1503373153
main:0:1503373154
main:1:1503373155
main:2:1503373156
main:3:1503373157
main:4:1503373158

答案:

package cn.itcast.demo.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;

public class Test2 {
	public static void main(String[] args) {
		
		// 创建一个信号灯,每个线程取数据的时候,取得信号灯,其他线程只能等待,当该线程取完数据之后就释放信号灯,这样其他线程又可以取
		final Semaphore semaphore = new Semaphore(1);
		
		// 队列
		final SynchronousQueue<String> queue = new SynchronousQueue<String>();
		// 创建十个线程
		for (int i=0; i<10; i++) {
			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) {
						e.printStackTrace();
					}
				}
			}).start();
		}
		
		System.out.println("begin:" + (System.currentTimeMillis()/1000));
		for (int i=0; i<10; i++) {		// 这行代码不能动
			String input = i + "";		// 这行代码不能动
			// 往队列中添加数据
			try {
				queue.put(input);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

// 这个类不能动
class TestDo {
	public static String doSome(String input) {
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String output = input + ":" + (System.currentTimeMillis()/1000);
		return output;
	}
}
begin:1503374218
Thread-0:0:1503374219
Thread-5:1:1503374220
Thread-1:2:1503374221
Thread-3:3:1503374222
Thread-4:4:1503374223
Thread-7:5:1503374224
Thread-6:6:1503374225
Thread-2:7:1503374226
Thread-8:8:1503374227
Thread-9:9:1503374228

 

posted @ 2017-08-22 11:53  半生戎马,共话桑麻、  阅读(117)  评论(0)    收藏  举报
levels of contents