This question already has answers here:
To multi-thread or not to multi-thread!
(5 answers)
Closed 8 years ago.
I have a general question.
I have been reading a Java book and I came across a program that uses Threads. Book stated that Threads are used for multiprocessing. I want to know that if I write :
Thread t=new Thread(new classname);
t.start;
//after it some GUI code to display the input received from user in run method
and I override run method to get input from user,then, will it wait for input and then perform GUI tasks like opening frame or it will perform both tasks simultaneously.
They'll happen simultaneously. (Unless you block one of the threads using locks or a semaphore.)
If the gui thread relies on the input processing of the other thread, you'll have a race condition. So you'll definitely want to block the gui thread until the other thread is done producing whatever the gui thread needs.
As for why threads are needed, well, it's so tasks can be done simultaneously so programs can do their jobs faster.
Related
This question already has answers here:
How do you kill a Thread in Java?
(17 answers)
Closed 2 years ago.
I want to create a thread to judge user codeļ¼
FutureTask<Integer> futureTask = new FutureTask(() -> run(type)); // run is a method
Thread thread = new Thread(futureTask);
thread.start();
As we all known, an infinite loop may be written in the user code, so the method run will be working all the time and the Thread thread will not stop. I want to terminate this thread after timeout duration. How can I terminate it instead of using Thread.stop because it's unsafe?
The correct way to deal with a thread that needs to be stopped is to design the thread's code so that it responds appropriately to being interrupted:
Long computations need to occasionally check the current thread's "interrupted" flag.
InterruptedException should be handled appropriately.
The thread application code's response to the interrupt should be to gracefully stop what it is doing1 and (typically) allow the thread to terminate.
(You could also use a custom flag implemented using a volatile shared variable instead of the interrupted flag. However, that doesn't deal with interrupting wait, sleep and similar operations, and is therefore a poor substitute for interrupts.)
The unsafe way is to call the deprecated Thread.stop() method. (The javadocs explain why it is unsafe, and we don't need to repeat that here.)
The (related) Thread.stop(Throwable) method was removed in Java 11; see:
Java 11 Removes stop() and destroy() Methods.
https://bugs.openjdk.java.net/browse/JDK-8204243
Unfortunately, there is nothing in between these two approaches for interrupting a thread.
If you cannot get your long running thread to cooperate, the safe alternative would be to run it in a separate process; e.g. using System.ProcessBuilder etcetera to run the java command. The (external) process could then be killed if it took too long. The downsides include:
An external process cannot access the current JVM's variables, etcetera. So you need to use a different mechanism to pass information between the parent and child processes.
Starting a new JVM is a lot more expensive than starting a new thread.
1 - For example, if the thread owns resources such as open files or sockets, it should release them. If it is performing an action for some other thread that will be waiting for the result, it should signal (in the appropriate way) that there will be no result. And so on.
Terminating thread from outside is ALWAYS unsafe and very strongly discouraged. You need to notify the thread that you want it to terminate and the thread must do it itself. That is done with method interrupt() of the class Thread. In your example it would be from the main code to call thread.interrupt() That will cause the interrupt flag to be raised in your thread. In your run method of your thread you should check for that flag (See methods interrupted() and isInterrupted() in the class Thread). Once you see that your flag is raised, break out of the loop and finish the method. That will stop your thread.
I was wondering how a 2 threads work on one method or block? And how does its process the instructions in the method or block? and would 2 threads work simultaneously or in a Round-Robin fashion to access the method or block?
This question already has an answer here:
JavaFX2: Can I pause a background Task / Service?
(1 answer)
Closed 8 years ago.
A worker thread is used to process a very long-running task. At the middle of task execution, a user interaction is needed to acquire inputs. As the inputs are supplied, the worker thread will resume execution. My problem is, the worker thread needs to be suspended, get inputs (shall we say through a dialog box - I am using the Dialogs API of JDK8u40 which must be facilitated by the JavaFX App Thread), and resume thereafter. The inputs are not supplied at the start due to dependency of certain situations, and inputs might be needed many times.
A typical example is, files are being copied from one directory to another. As the files are copied, a file with the same file name exists in the destination directory, thus a user interaction is needed to rename the file or skip file copying to avoid file name conflict. In this scenario, the worker thread is supposed to execute file copying, and is needed to be suspended to acquire inputs from user (must be facilitated by the JavaFX App Thread) before proceeding. Platform.runlater(() -> {}); can't do this kind of situation, for it would just queued the Runnable object to be ran at some time in the future.
How to facilitate this scenario? I am new to JavaFX concurrency.
You can use the wait notify mechanism as described here: http://www.avajava.com/tutorials/lessons/how-do-i-use-the-wait-and-notify-methods.html.
When an interaction is needed a runnable is launched through ui thread to prompt the user. The worker thread calls wait. The ui thread eventually gets the user input and notifies the working thread which continues his job according to the message it receives. The difference here is that you do not need to create two threads as the ui thread already exists.
This question already has answers here:
How Thread run starts?
(5 answers)
Closed 8 years ago.
....As the title of the questions says, I want to know what all things internally happen when we call Thread.start() and when does the start method return and main resume to execute. What all things internally get triggered like registering the thread with scheduler etc..? Also why executors are used ?
When you call t.start the JVM creates a new thread of execution (with its own stack). This is done by native code, it is not done in Java. So then the JVM itself calls t.run in the newly created thread of execution. This is usually a source of confusions (for starters) as the Java class Thread has the same name as the concept thread of execution. I guess one can think of these two as: the latter is the 'physical concept', the former is its 'abstract Java representation as a class'.
It usually takes some time between you calling t.start in the current thread of execution, and the JVM calling t.run in the newly created thread of execution; there's some time lag there as creating a new thread of execution is a somewhat heavy operation.
Thread.start
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
This question already has answers here:
The difference between Executors.newSingleThreadExecutor().execute(command) and new Thread(command).start();
(6 answers)
Closed 9 years ago.
What is the advantage of using
Executors.newSingleThreadExecutor().submit(job);
than
job.run();
where job is an instance of Runnable class.
Writing literally
Executors.newSingleThreadExecutor().submit(job);
is pointless: it's just the wrong way to do
new Thread(job).start();
As opposed to the latter, the former will leave the thread hanging on until the Executor Service is finalized.
The advantage of using an Executor Service comes about when you keep it around as an instance/class variable and reuse it for many submitted tasks. The Executor Service must be properly shutdown when you are done with it.
More generally, the difference between submitting tasks to an executor service and just running the tasks is in the achieved concurrency. Whether that results in any advantage is highly specific to the job being submitted: it may also be useless or even broken (causing data races, deadlocks, etc.).
The difference is same as in new Thread(job).start() and job.run(). When you submit the job for execution, the job runs in one of the available thread of the executor. Calling job.run() is simply like any other method call which does not run in a separate thread but rather on the calling thread.
One of the advantage is that Executors.newSingleThreadExecutor reuse the Thread instance to speed up the starting of the other jobs.