SynchronousQueue实现两个线程之间的数据传递共享
解决方法:
实现线程threadA存放数据到异步队列SynchronousQueue,如果没有其它线程从队列中获取数据,那threadA就进入阻塞状态。如果threadB获取异步队列的数据后threadA就恢复可执行状态。
如果threadB获取数据时队列没数据,那threadB就进入阻塞状态,当threadA往队列里添加数据时threadB才进入可执行状态。
1.测试类
import java.util.concurrent.SynchronousQueue;
public class Test{
public static void main(String[] args) {
try {
SynchronousQueue s=new SynchronousQueue();
//往SynchronousQueue队列添加数据的线程
TestA testA = new TestA(s);
Thread threadA = new Thread(testA);
threadA.start();
//往SynchronousQueue队列获取数据的线程
TestB testB= new TestB(s);
Thread threadB = new Thread(testB);
threadB.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.线程threadA,往队列里添加数据
import java.util.concurrent.SynchronousQueue;
public class TestA implements Runnable{
public SynchronousQueue s=new SynchronousQueue();
public TestA(SynchronousQueue s) {
super();
this.s = s;
}
@Override
public void run() {
try {
System.out.println("step1");
s.put("共享数据");
System.out.println("数据已存入SynchronousQueue队列");
System.out.println("step2");
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.线程threadB,从队列里获取数据
import java.util.concurrent.SynchronousQueue;
public class TestB implements Runnable{
public SynchronousQueue s=new SynchronousQueue();
public TestB(SynchronousQueue s) {
super();
this.s = s;
}
@Override
public void run() {
try {
System.out.println("step3");
System.out.println("获取SynchronousQueue队列的值:"+s.take());;
System.out.println("step4");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.结果
step1
数据已存入SynchronousQueue队列
step3
step2
获取SynchronousQueue队列的值:共享数据
step4