import java.util.Random;
import java.util.concurrent.Semaphore;
public class Test {
public static void main(String[] args){
Semaphore semaphore = new Semaphore(1);
final boolean[] shouldThread1 = {true};
int cycleTime = 20;
new Thread(new Runnable() {
@Override
public void run() {
Random random = new Random();
for(int i=1;i<=cycleTime;i++){
while (true){
if(shouldThread1[0]){
try {
semaphore.acquire();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}
}
for(int j=1;j<=10;j++){
System.out.println( "loop" + i + " 線程1: " + j );
try {
Thread.sleep( random.nextInt( 20 ) );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
shouldThread1[0] =false;
semaphore.release();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Random random = new Random();
for(int i=1;i<=cycleTime;i++){
while (true){
if( !shouldThread1[0] ){
try {
semaphore.acquire();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}
}
for(int j=1;j<=20;j++){
System.out.println( " loop" + i + " 線程2: "+ j );
try {
Thread.sleep( random.nextInt( 40 ) );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
shouldThread1[0]=true;
semaphore.release();
}
}
}).start();
}
}