package zhu.suo;
/*
* 2.十个线程乱序执行一个打印,每个打印需要一秒
* */
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
public class Test2 {
public static void main(String[] args) {
final SynchronousQueue sque= new SynchronousQueue<String>();//此同步队列,把tabke和put封装为原子性
final Semaphore semaphore = new Semaphore(1);
for(int i=1;i<11;i++)
{
new Thread(
new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();//获取一个信号
Object v = (Object) sque.take();
String output = print(v);
System.out.println("线程名:"+Thread.currentThread().getName()+","+output);
semaphore.release();//释放一个
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
).start();
}
for(int i=1;i<11;i++)
{
try {
sque.put(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//打印
static String print(Object v)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return v+",cureentTime:"+System.currentTimeMillis()/1000;
}
}
/*
* 2.十个线程乱序执行一个打印,每个打印需要一秒
* */
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
public class Test2 {
public static void main(String[] args) {
final SynchronousQueue sque= new SynchronousQueue<String>();//此同步队列,把tabke和put封装为原子性
final Semaphore semaphore = new Semaphore(1);
for(int i=1;i<11;i++)
{
new Thread(
new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();//获取一个信号
Object v = (Object) sque.take();
String output = print(v);
System.out.println("线程名:"+Thread.currentThread().getName()+","+output);
semaphore.release();//释放一个
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
).start();
}
for(int i=1;i<11;i++)
{
try {
sque.put(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//打印
static String print(Object v)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return v+",cureentTime:"+System.currentTimeMillis()/1000;
}
}