某天听到学长说找工作面试时遇到某互联网公司要求写生产者消费者模式加任意设计模式。
即然以这个为题,我顺手写了一份单例设计模式,加奇偶数打印的生产者消费者的简单案例。
先说解题思路:生产者消费者模式准备采用简单的synchrnoized的同步代码块去实现,同时同步监视器准备采用单例对象替代常规object对象。
话不多说先上单例设计模式的代码生成我准备使用的同步监视器对象
class Single{
public static Single instance;
public static Single test(){
if(instance==null){
synchronized (Single.class){
if(instance==null){
instance=new Single();
}
}
}
return instance;
}
//在这里使用private使外面的调用者不可以简单的使用new对象来生成对象
private Single() {
}
}
这里写好了同步监视器对象
下面开始生成者消费者模式
public class Communicate {
private Single instance = Single.test();
//以上的代码已经能够实现单例了
//再继续写一下生产者消费者模式
private int i=0;
public void odd(){
synchronized (instance){
while(i<10) {
if (i % 2 != 0) {
System.out.println("奇数"+i);
i++;
instance.notify();
}else{
try {
instance.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void even(){
synchronized (instance){
while(i<10) {
if (i % 2 == 0) {
System.out.println("偶数"+i);
i++;
instance.notify();
}else{
try {
instance.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
再来开启两个线程去调用
public static void main(String[] args) {
final Communicate communicate=new Communicate();
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
communicate.odd();
}
});
Thread thread2=new Thread(new Runnable() {
@Override
public void run() {
communicate.even();
}
});
thread1.start();
thread2.start();
}
打印结果如下:
偶数0
奇数1
偶数2
奇数3
偶数4
奇数5
偶数6
奇数7
偶数8
奇数9
Process finished with exit code 0
好了,简单的生产者消费者模式就写好了。