多线程与并发面试题2

package skytest;


import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class ThreadTest2 {


public static void main(String[] args) {
//信号灯
final Semaphore semaphore = new Semaphore(1);

final SynchronousQueue queue = new SynchronousQueue();
//锁
final Lock lock = new ReentrantLock();


for(int i=0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
//semaphore.acquire();
lock.lock();
String input=queue.take();
String output=TestDo.doSome(input);
System.out.println(Thread.currentThread().getName()+":"+output);
lock.unlock();
//semaphore.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 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 (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

String output=input+":"+System.currentTimeMillis()/1000;
return output;
}
}

你可能感兴趣的:(多线程与并发)