当前位置: 首页>后端>正文

SynchronousQueue同步队列

SynchronousQueue同步队列,第1张
SynchronousQueue同步队列,第2张
SynchronousQueue同步队列,第3张

package unit5;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.SynchronousQueue;

import java.util.concurrent.TimeUnit;

public class Java52 {

public static void main(String[] args) {

// SynchronousQueue同步队列:没有容量、不存储元素、put进去一个元素、必须从里面take出来一个元素、才能往里边放一个元素、否则不能再put进去

BlockingQueue blockingQueue = new SynchronousQueue();

new Thread(()->{

try {

System.out.println(Thread.currentThread().getName() + "put 1");

blockingQueue.put(1);

System.out.println(Thread.currentThread().getName() + "put 2");

blockingQueue.put(2);

System.out.println(Thread.currentThread().getName() + "put 3");

blockingQueue.put(3);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

}, "T1").start();

new Thread(()->{

try {

TimeUnit.SECONDS.sleep(3);

System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());

TimeUnit.SECONDS.sleep(3);

System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());

TimeUnit.SECONDS.sleep(3);

System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

}, "T2").start();

}

}


https://www.xamrdz.com/backend/3pe1940568.html

相关文章: