here's my problem: I have an application that launches a simulated server locally. The output of this operation is redirected to a log file and I want to look for a specific pattern in this log file while it's being written.
I already implemented the tail -f simulation (I have to work on windows), but I can't get the two threads to work fine simultaneously.
Here's a sample (in the main) :
server.launch();
patternFinder.start();
The patternFinder extends Thread and here is what its run method looks like:
public void run() {
while (true) {
//tail -f implementation
//I'll set a timeout when I can get it
//to work (the pattern is supposed to be found)
}
}
If I put patternFinder.join()
after the start()
, the server will pause its execution and wait for the patternFinder to return (but he won't because nothing is being written in the log). But the child thread need to block the main thread because we don't want any instruction to be executed until the pattern is found (or the timeout limit has been reached).
Any ide开发者_如何学运维as?
(ps: first post so don't hesitate to tell me if I did something wrong or if you need any more details)
You should use Events to coordinate your threads. You can wait on an event in the main thread and set/reset it on your child thread when things have been found.
You can use Manual or AutoResetEvents for that. Not sure what they are called in Java, but I'm sure you can find that out.
Just so this questioned doesn't stay unanswered I found some kind of a workaround but never figured what was really the problem.
So apparently the problem was that I was launching my server via a ProcessBuilder with a command looking like this java [arguments] [classpath] fileToLaunch
. I tried a lot of things but the only one that worked was to change the command to cmd /C start java [arguments] [classpath] fileToLaunch
so it starts the server in a new window and then everything worked as expected.
If ever someone can explain that mystery to me, feel free to provide a new answer that still could be accepted.
精彩评论