- 使用阻塞队列实现: 子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100次,如此循环50次
package BlockQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
final Business bus=new Business();
Thread sub=new Thread(new Runnable(){
@Override
public void run() {
for(int n=0;n<50;n++){
try {
bus.sub(n);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
sub.start();
for(int n=0;n<50;n++){
bus.main(n);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Business{
BlockingQueue<Integer> b1=new ArrayBlockingQueue<Integer>(1);
BlockingQueue<Integer> b2=new ArrayBlockingQueue<Integer>(1);
{
try {
System.out.println("构造函数");
b2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sub(int n) throws InterruptedException{
b1.put(1);
for(int i=0;i<10;i++){
System.out.println("sub 循环第"+i+"次,loop"+n);
}
b2.take();
}
public void main(int n) throws InterruptedException {
b2.put(1);
for(int i=0;i<10;i++){
System.out.println("main 循环第"+i+"次 ,loop "+n);
}
b1.take();
}
}
}