This question already has answers here:
What's the difference between Thread start() and Runnable run()
(14 answers)
Closed 5 years ago.
I wont to run my thread in background but it keeps blocking UI.
In methods login() and dostaff() I use selenium webdriver to get data and display it in label, after that I refresh page and thread sleeps for 60000ms;
public static class Moderate implements Runnable {
public void run() {
login();
while (true) {
dostaff();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void login(){....};
private void dostaff(){....};
}
and I call it:
public void ModerateLoop(javafx.scene.control.Label lbl) {
this.displayLabel = lbl;
Moderate thread = new Moderate();
thread.run();
}
because you are calling the method run
thread.run();
so this is blocking the invoking thread until your code in the run method is done.
you need instead to start the thread
thread.start();
Related
This question already has answers here:
Running Thread by calling start() and run(), what is the difference?
(7 answers)
Second thread doesn't start in producer consumer example
(1 answer)
child thread blocks parent thread in java
(1 answer)
Closed 5 years ago.
When I run below code, Producer run() method starts and puts random numbers to jobs queue but Consumer run() method never runs. What is the main problem here?
Here is Main class;
public static LinkedBlockingQueue<Integer> jobs = new LinkedBlockingQueue<>();
public static void main(){
MessageProducer producer = new MessageProducer(jobs);
Thread producerThread = new Thread(producer);
producerThread.run();
MessageConsumer consumer = new MessageConsumer(jobs);
Executor executor = Executors.newFixedThreadPool(3);
executor.execute(consumer);
}
Producer;
public class MessageProducer implements Runnable {
public LinkedBlockingQueue<Integer> jobs;
public MessageProducer(LinkedBlockingQueue<Integer> jobs){
this.jobs = jobs;
}
#Override
public void run() {
while(true) {
try {
jobs.put((int) (Math.random() * 10));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Consumer;
public class MessageConsumer implements Runnable{
public LinkedBlockingQueue<Integer> jobs;
public MessageConsumer(LinkedBlockingQueue<Integer> jobs) {
this.jobs = jobs;
}
#Override
public void run() {
while(true) {
System.out.println("Executing " + jobs.poll());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Don't invoke Thread.run(). It doesn't start the thread. It invokes the run() method that in your case is an infinite loop.
So the JVM stays stucked on producerThread.run(); that never returns.
Instead invoke Thread.start() that will be in charge to invoke the run() method.
The Thread.start() javadoc states indeed :
Causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread.
Is there a way I can do a similar task like the android OS or java AWT thread where a task is run on a particular thread regardless of which thread of which thread the method was called from e.g. repaint().
private Thread thread;
public void startThread(){ //method which start's my thread
thread = new Thread(new Runnable(){
doSomething();
});
thread.start()
}
public void submitTask(Runnable runnable){
//run the runnable task on the thread "thread"
}
How can I achieve something like this, on a situation where I have more then one active thread
How I've dealt with this scenario before is to create a work queue and a thread which processes tasks that get added to it. So any thread can add a work item to the queue and the same thread will process it regardless of what thread added the work item.
public class MyClass {
private LinkedBlockingQueue<MyTask> myTaskProcessingQueue;
public MyClass() {
myTaskProcessingQueue = new LinkedBlockingQueue<MyTask>();
new MyTaskWorker().start();
}
public void processTask(MyTask myTask) {
myTaskProcessingQueue.put(myTask);
}
private class MyTaskWorker extends Thread {
#Override
public void run() {
while (true) {
try {
processMyTask(myTaskProcessingQueue.take());
} catch (InterruptedException ie) {
// handle it
}
}
}
private void processMyTask(MyTask myTask) {
// do work
}
}
}
This question already has answers here:
What is the difference between Thread.start() and Thread.run()?
(9 answers)
Closed 8 years ago.
i am new to java. I have two classes that looks like:
public class hsClient implements Runnable {
public void run() {
while(true){
}
}
}
public class hsServer implements Runnable {
public void run() {
while(true){
}
}
}
If i try to start both classes as Thread it wont start the second thread. It looks like he stuck in the first one.
This is my main class:
public static void main(String[] args) throws IOException {
hsClient client = new hsClient();
Thread tClient = new Thread(client);
tClient.run();
System.out.println("Start Client");
hsServer server = new hsServer();
Thread tServer = new Thread(server);
tServer.run();
System.out.println("Start Server");
}
If i run my code it only prints "Start Client" but not "Start Server" on the console
Replace tClient.run() with tClient.start() and tServer.run() with tServer.start().
Calling the run method directly executes it in the current thread instead of in a new thread.
To start a thread use the start method.
Thread tClient = new Thread(client);
tClient.start(); // start the thread
More info on threads can be found e.g. in the JavaDoc
This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 9 years ago.
public Thread thread = new Thread();
public void start() {
running = true;
thread.start();
}
public void run() {
while(running) {
System.out.println("test");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
My problem is that the program will not print out "test" nor will it seem to loop despite 'running' being true. Is there a way I can continuously loop in the run method?
You haven't actually asked run() to be called. All you've done is declare a run() method unrelated to the Thread.
Put your run() method in a Runnable and pass that to the Thread.
public Thread thread = new Thread(new Runnable() {
public void run() {
while (running) {
System.out.println("test");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
The problem appears to be that you aren't running the run method that you think you're running in the thread.
First, you've created a Thread called thread. In your class's start method, you set running to true and call thread.start(). But that just calls Thread's run() method, which does nothing.
public void run()
If this thread was constructed using a separate
Runnable run object, then that Runnable object's run method is called;
otherwise, this method does nothing and returns.
You aren't calling your own run method.
You have created a run method. I can't see your class definition here, but I'm assuming that your class implements Runnable. You need to send an instance of your class as an argument to the Thread, by using the Thread constructor that takes a Runnable. Then the Thread will know to run your Runnable's run() method.
Well you need to call start() to start the thread. Otherwise neither running will be true
nor thread.start() get executed. Well i can guess you were intended to do something like this:
class MyTask implements Runnable
{
boolean running = false;
public void start() {
running = true;
new Thread(this).start();
}
public void run() {
while(running) {
System.out.println("test");
try {
Thread.sleep(1000);
// you were doing thread.sleep()! sleep is a static function
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new MyTask().start();
}
}
This question already has answers here:
How to start/stop/restart a thread in Java?
(9 answers)
Closed 7 years ago.
I have the following thread:
public void start() {
isRunning = true;
if (mainThread == null) {
mainThread = new Thread(this);
mainThread.setPriority(Thread.MAX_PRIORITY);
}
if (!mainThread.isAlive()) {
try {
mainThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
At some point I want to stop it's operation:
public void stop() {
isRunning = false;
System.gc();
}
When calling start() again the following exception is thrown:
java.lang.IllegalThreadStateException
Pointing the mainThread.start() line of code.
What is the best way to start/stop a thread? how can I make this thread reusable?
Thanks!
Once a thread stop you cannot restart it in Java, but of course you can create a new thread in Java to do your new job.
The user experience won't differ even if you create a new thread or restart the same thread(this you cannot do in Java).
You can read the website for API specification http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html
What you might be looking for is Interrupts. An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
To know more about interrupts read the Java tutorial guide http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
From your code slice it seems that you are using a Runnable class with a Thread attribute. Instead of using stop/start you might use suspend/resume below:
private boolean isPaused;
public void run() {
while (!isRunning) {
// do your stuff
while (isPaused) {
mainThread.wait();
}
}
}
public void suspend() {
isPaused = true;
}
public void resume() {
isPaused = false;
mainThread.notify();
}
I did not add the synchronized blocks to keep the code small, but you will need to add them.