繁体   English   中英

如何正确使用notify和wait

[英]How to properly use notify and wait

如何正确使用通知和等待。 我只有两个线程来测试我的逻辑。 是不是如下我创建一个线程,它将执行类型为 get file_1 file_2的命令并创建type cmd 的file3 我的第一个任务没有file_2因此它将在条件谓词上处于等待状态,该条件谓词检查两个文件是否都存在文件上的 .exists() 方法。 第二个线程将创建file_2并通知第一个线程然后另一个线程将唤醒并执行他的工作。 问题是在等待的线程唤醒后,它没有他的工作,而是另一个线程的工作。 例如,如果Thread-1必须执行file1 file2 > file3并且它处于等待状态。 并且Thread-2必须执行file3 file4 > file2所以它创建file2并通知Thread-1 线程 1 醒来后,它有file3 fil4 > file2而不是他的文件。 我正在将所有内容转储到控制台,当两个线程从命令文件中获取任务时,它们会获取正确的任务,但它们没有相同的任务,但是在Thread-1唤醒后,它具有Thread-2任务。 有人可以帮助我了解如何在这种情况下以及在任何其他情况下使用等待和通知。 我已经在实践中阅读了 Java Concurrency,但他们只在那里放置和使用方法并等待并通知 google 中的示例是幼稚的,它们按预期工作。 提前致谢。

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class MyTaskManager {
    private static AtomicInteger id = new AtomicInteger();
    private static String[] in;
    private static String cmd;
    private static Task task;
    private static Process process;
    private static MyTaskManager taskManager;

    public static void main(String[] args) {
        taskManager = new MyTaskManager();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Assign work
                    synchronized (taskManager) {
                        String line = Files.readAllLines(Paths.get("commands.txt"))
                                .get(id.get());
                        id.getAndIncrement();
                        in = line.split(" ");
                        cmd = in[0] + " " + in[1] + " " + in[2] + " " + in[3] + " " + in[4];
                        task = new Task(cmd);
                        System.out.println(cmd);
                    }

                    // After the thread is woked up it checks the condition again
                    // but this time it is taken the other thread object
                    synchronized (taskManager) {
                        while (!task.checkCondition(task)) {
                            System.out.println("Waiting thread " + Thread.currentThread().getName());
                            System.out.println("Write file in wait " + task.getOutput_file());
                            System.out.println("---------------------------------");

                            taskManager.wait();
                            System.out.println(Thread.currentThread().getName() + " after sleep");
                        }
                    }

                    process = Runtime.getRuntime()
                            .exec("cmd /c start cmd.exe /k \"" + task.getCmd() + "\"");
                    process.waitFor();

                    synchronized (taskManager) {
                        taskManager.notifyAll();
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Assign work
                    synchronized (taskManager) {
                        String line = Files.readAllLines(Paths.get("commands.txt"))
                                .get(id.get());
                        id.getAndIncrement();
                        in = line.split(" ");
                        cmd = in[0] + " " + in[1] + " " + in[2] + " " + in[3] + " " + in[4];
                        task = new Task(cmd);
                        System.out.println(cmd);
                    }
                    process = Runtime.getRuntime()
                            .exec("cmd /c start cmd.exe /k \"" + task.getCmd() + "\"");

                    process.waitFor();
                    synchronized (taskManager) {
                        taskManager.notifyAll();
                        System.out.println("Notifying " + Thread.currentThread().getName());
                    }

                } catch (IOException | InterruptedException e) {
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
            }
        });
        BlockingQueue<Runnable> worksQueue = new
                ArrayBlockingQueue<>(10);
        RejectedExecutionHandler rejectionHandler = new
                RejectedExecutionHandlerImpl();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 20,
                TimeUnit.SECONDS, worksQueue, rejectionHandler);
        executor.prestartAllCoreThreads();

        List<Runnable> taskGroup = new ArrayList<>();
        taskGroup.add(t);
        taskGroup.add(t1);

        worksQueue.add(new MultiRunnable(taskGroup));

        executor.shutdown();
    }
}

   boolean checkCondition(Task task) {
        String[] in = task.cmd.split(" ");
        File dep1 = new File(in[1]);
        File dep2 = new File(in[2]);

        return dep1.exists() && dep2.exists();
    }

在您的情况下,相互 wait-notify 调用的问题在于,一个线程可以完成其工作并在另一个线程调用wait之前调用notify 通知不会“记住”,因此如果在实际wait之前调用通知,则等待线程将永远等待(好吧,直到另一个通知)。

如果我没记错的话,你想让 T1 做一些工作,等待 T2 的一些通知,然后做一些其他的 + 退出。 如果这是正确的,那么使用CountDownLatchSemaphore会简单得多

两者都可以取消上述赛车条件的影响。 当其他线程正在等待它这样做时,倒计时闩锁可以“倒计时”,或者在这之前会导致“等待线程”永远不必等待,因为“门已经打开”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM