堵塞队列(BlockingQueue)实现互斥
阻塞队列(BlockingQueue)实现互斥
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockCom {
public static void main(String[] args) {
final int times = 10;
final BqSay say = new BlockCom().new BqSay();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<=times;i++){
say.sub(i);
}
}
}).start();
for(int i=1;i<=times;i++){
say.main(i);
}
}
class BqSay {
private BlockingQueue<Integer>bqo = new ArrayBlockingQueue<Integer>(1);
private BlockingQueue<Integer>bqt = new ArrayBlockingQueue<Integer>(1);
{
try{
bqt.put(1);
}catch(Exception e){
e.printStackTrace();
}
}
public void main(int i){
try{
bqt.put(1);
for(int j=1;j<=10;j++){
System.out.println(Thread.currentThread().getName()+"主线程第"+i+"趟第"+j+"次");
}
bqo.take();
}catch(Exception e){
e.printStackTrace();
}
}
public void sub(int i){
try{
bqo.put(1);
for(int j=1;j<=5;j++){
System.out.println(Thread.currentThread().getName()+"子线程第"+i+"趟第"+j+"次");
}
bqt.take();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockCom {
public static void main(String[] args) {
final int times = 10;
final BqSay say = new BlockCom().new BqSay();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<=times;i++){
say.sub(i);
}
}
}).start();
for(int i=1;i<=times;i++){
say.main(i);
}
}
class BqSay {
private BlockingQueue<Integer>bqo = new ArrayBlockingQueue<Integer>(1);
private BlockingQueue<Integer>bqt = new ArrayBlockingQueue<Integer>(1);
{
try{
bqt.put(1);
}catch(Exception e){
e.printStackTrace();
}
}
public void main(int i){
try{
bqt.put(1);
for(int j=1;j<=10;j++){
System.out.println(Thread.currentThread().getName()+"主线程第"+i+"趟第"+j+"次");
}
bqo.take();
}catch(Exception e){
e.printStackTrace();
}
}
public void sub(int i){
try{
bqo.put(1);
for(int j=1;j<=5;j++){
System.out.println(Thread.currentThread().getName()+"子线程第"+i+"趟第"+j+"次");
}
bqt.take();
}catch(Exception e){
e.printStackTrace();
}
}
}
}