不需要就算了,Balk 即 停止并返回。

    我们在并发编程的时候,经常会遇到这样的情况,就是我们并发请求,但是只要一个回应,谁先来就用谁,后来的就扔掉。现实中就是,老师让我们回答问题,问:1+1 等于多少? 然后抢答,你的手速比较慢,小明先回答了:2。虽然你内心极度不甘心,虽然你知道等于 10 但是你没有机会了。

    好了,小葵花课堂开课了,我们如何在程序中实现这个呢?其实很简单,用一个 flag 来保存,是否有人抢到。如果有人抢到了就把 flag 置为true。那么后来的自然就不能去响应了。这个就要保证修改 flag 的时候是 synchronized 。
    在举个例子,我们平时用的word,会有自动保存的功能。保存线程每隔1秒保存一下,但是如果没有改变是不需要再次保存的。

    Data 最关键的就是 changed 这个 flag。change 和 save 都是 synchronized 的方法。保证安全。

    1. public class Data {
    2. private String fileName;
    3. private String content;
    4. private boolean changed;
    5. public Data(String fileName, String content) {
    6. this.fileName = fileName;
    7. this.content = content;
    8. }
    9. public synchronized void change(String newContent) {
    10. this.content = newContent;
    11. changed = true;
    12. }
    13. public synchronized void save() throws IOException {
    14. if (changed == true) {
    15. doSave();
    16. changed = false;
    17. } else {
    18. System.out.println(Thread.currentThread().getName()+"-- no change");
    19. return;
    20. }
    21. }
    22. private void doSave() throws IOException {
    23. System.out.println(Thread.currentThread().getName()+"--"+content);
    24. Writer writer = new FileWriter(fileName);
    25. writer.write(content);
    26. writer.close();
    27. }
    28. }

    SaverThread 线程 每一秒保存一下。

    1. public class SaverThread extends Thread {
    2. private final Data data;
    3. public SaverThread(String name, Data data) {
    4. super(name);
    5. this.data = data;
    6. }
    7. @Override
    8. public void run() {
    9. super.run();
    10. try {
    11. while (true) {
    12. data.save();
    13. Thread.sleep(1000);
    14. }
    15. } catch (IOException e) {
    16. e.printStackTrace();
    17. } catch (InterruptedException e) {
    18. e.printStackTrace();
    19. }
    20. }
    21. }

    ChangerThread 线程 不定时写入。

    1. public class ChangerThread extends Thread {
    2. private final Data data;
    3. private Random random = new Random();
    4. public ChangerThread(String name, Data data) {
    5. super(name);
    6. this.data = data;
    7. }
    8. @Override
    9. public void run() {
    10. super.run();
    11. Random random = new Random();
    12. long num = 0;
    13. try {
    14. while (true) {
    15. String str = "change:" + num++;
    16. data.change(str);
    17. Thread.sleep(random.nextInt(2000));
    18. }
    19. } catch (InterruptedException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    1. public class Main {
    2. public static void main(String[] args) {
    3. Data data = new Data("data.txt", "empty");
    4. new ChangerThread("ChangerThread",data).start();
    5. new SaverThread("SaverThread",data).start();
    6. }
    7. }

    实行结果如下:

    image.png