并发编程现场编程题

文章通过两个示例展示了Java中如何使用wait、notify和synchronized关键字实现线程间的协作。第一个例子是生产者消费者问题的解决方案,使用CopyOnWriteArrayList作为缓冲区,保证了线程安全。第二个例子详细说明了如何让三个线程按照ABC顺序循环打印,通过共享变量和wait/notify机制实现了线程间的同步和通信。
摘要由CSDN通过智能技术生成

1 使用wait、notify和synchronized实现生产者消费者

package org.example.pc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class SafeQueue {
    public static final int MAX_COUNT = 10;

    List<String> queue = new CopyOnWriteArrayList<>();

    public void put(String e) {
        queue.add(e);
    }

    public String take() {
        synchronized (queue) {
            String element = queue.get(0);
            queue.remove(element);
            return element;
        }
    }

    public int size() {
        return queue.size();
    }
}
package org.example.pc;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Producer implements Runnable {
    private SafeQueue safeQueue;

    private String element;

    public Producer(SafeQueue safeQueue, String element) {
        this.safeQueue = safeQueue;
        this.element = element;
    }

    @Override
    public void run() {
        // important, 一定要抢到safeQueue的前提下才能wait和notify
        synchronized (safeQueue) {
            if (safeQueue.MAX_COUNT - safeQueue.size() < 5) {
                try {
                    safeQueue.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            for (int i = 0; i < 5; i++) {
                try {
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                safeQueue.put(element);
            }
            if (safeQueue.size() > 0) {
                safeQueue.notify();
            }
        }
    }
}
package org.example.pc;

public class Consumer implements Runnable {
    private SafeQueue safeQueue;

    public Consumer(SafeQueue safeQueue) {
        this.safeQueue = safeQueue;
    }

    @Override
    public void run() {
        synchronized (safeQueue) {
            while (true) {
                if (safeQueue.size() == 0) {
                    try {
                        safeQueue.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                String element = safeQueue.take();
                System.out.println(element);
                if (safeQueue.size() < SafeQueue.MAX_COUNT) {
                    safeQueue.notify();
                }
            }
        }
    }
}
package org.example.pc;

public class Client {
    public static void main(String[] args) {
        SafeQueue safeQueue = new SafeQueue();

        for (int i = 0; i < 4; i++) {
            new Thread(new Producer(safeQueue, String.valueOf(i))).start();
        }

        for (int i = 0; i < 1; i++) {
            new Thread(new Consumer(safeQueue)).start();
        }
    }
}

2 ABC三个线程分别打印ABC,现实现能够循环N次打印ABC

V2.0 使用wait()和notifyAll()

2.1 优缺点

进程可以终止。
便于理解和实现。

2.2 代码

package org.example;

public class SkMain {
    public static void main(String[] args) {
        ABCPrinter printer = new ABCPrinter();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    printer.printA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    printer.printB();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    printer.printC();
                }
            }
        }).start();
    }
}

class ABCPrinter {
    private volatile int value = 1;

    public void printA() {
        synchronized (this) {
            while(value != 1) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("A");
            value++;
            notifyAll();
        }
    }

    public void printB() {
        synchronized (this) {
            while(value != 2) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("B");
            value++;
            notifyAll();
        }
    }

    public void printC() {
        synchronized (this) {
            while(value != 3) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("C");
            value = 1;
            notifyAll();
        }
    }
}

Reference

https://blog.csdn.net/realYuzhou/article/details/108367264

V1.0 面试挂的比较low的版本,只使用synchronized

1.1 缺点

程序不会终止

1.2 代码

A.java

package org.example;

public class A implements Runnable {
    private B b;

    private C c;

    private int N = 5;

    private boolean isFinish = false;

    @Override
    public void run() {
        while (N > 0) {
            synchronized (c) {
                if (N ==5 && !isFinish) {
                    core();
                } else if (c.isFinish() && !isFinish) { // wait c finish.
                    core();
                }
            }
        }
    }

    private void core() {
        isFinish = false;
        System.out.println("A");
        N--;
        isFinish = true;
        b.setFinish(false);
    }

    public void setFinish(boolean finish) {
        isFinish = finish;
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void setC(C c) {
        this.c = c;
    }

    public void setB(B b) {
        this.b = b;
    }
}

B.java

package org.example;

public class B implements Runnable {
    A a;

    C c;

    private boolean isFinish = false;

    @Override
    public void run() {
        while(true) {
            synchronized (a) {
                if (a.isFinish() && !isFinish) {
                    isFinish = false;
                    System.out.println("B");
                    isFinish = true;
                    c.setFinish(false);
                }
            }
        }
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void setFinish(boolean finish) {
        isFinish = finish;
    }

    public void setA(A a) {
        this.a = a;
    }

    public void setC(C c) {
        this.c = c;
    }
}

C.java

package org.example;

public class C implements Runnable {
    B b;

    A a;

    private boolean isFinish = false;

    @Override
    public void run() {
        while (true) {
            synchronized (b) {
                if (b.isFinish() && !isFinish) {
                    isFinish = false;
                    System.out.println("C");
                    isFinish = true;
                    a.setFinish(false);
                }
            }
        }
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void setFinish(boolean finish) {
        isFinish = finish;
    }

    public void setB(B b) {
        this.b = b;
    }

    public void setA(A a) {
        this.a = a;
    }
}

Main.java

package org.example;

public class Main {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();

        b.setA(a);
        a.setB(b);
        c.setB(b);
        c.setA(a);
        b.setC(c);
        a.setC(c);

        Thread threadA = new Thread(a);
        Thread threadB = new Thread(b);
        Thread threadC = new Thread(c);

        threadA.start();
        threadB.start();
        threadC.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值