Java starting two threads? [duplicate] - java

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

Related

Thread not executing [duplicate]

This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 5 years ago.
This thread does not execute when I run the program. I'm wondering if there's something wrong with the code.
public static void writeToFileAsync(final String saveState, final String fileName) {
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
start();
}
};
}
Also, why does NetBeans want me to put that semicolon next to the second curly brace after the start() call?
Start a thread
Your thread will only start if you call the start method explicitly. Here is the documentation Thread#start. The start method will then internally invoke the run method of your Thread.
Your code could then look like this:
public static void writeToFileAsync(final String saveState, final String fileName) {
// Create the thread
Thread fileWriter = new Thread() {
#Override
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
// Do nothing
}
}
};
// Start the thread
fileWriter.start();
}
And you probably want to remove the start(); call inside your run method.
Semicolon
You need the ; after the Thread creation because you are using an assignment:
Thread fileWriter = new Thread() { ... };
The concept you are using here is called anonymous class. Basically it is the same as if creating a new class like:
public class FileWriter extends Thread {
#Override
public void run() {
...
}
}
And then using it like:
Thread fileWriter = new FileWriter();
However an important difference is that your anonymous class has access to your local variables (the scope of that method). And that it is anonymous, so it's like a small single-time usage class.
Your call to the start method cannot be inside the body of your thread. You can do this:
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
}
}.start(); // call the start method outside the body of you thread.
And about the semicolon, you are creating an Anonymous Class and that is its syntax:
Because an anonymous class definition is an expression, it must be
part of a statement... (This explains why there is a semicolon after
the closing brace.)
A thread simply works this way. Below is a piece of code where a thread is created as an anonymous inner type where the run method is overrided. Then by calling the start method , it automatically called the overrided run method.
public class ThreadTest {
Thread t = new Thread(){
public void run() {
System.out.println("thread is running");
};
};
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.t.start();
}
}

Why UI freezes? [duplicate]

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();

Establishing a Connection Asynchronously [duplicate]

This question already has answers here:
What is the difference between Thread.start() and Thread.run()?
(9 answers)
Closed 6 years ago.
I was told to run all of my MySQL connection processes on another thread besides the main thread to avoid the main thread from being stuck on a process that takes a few seconds to process.
Therefore, I established a ConnectionPool in a separate thread, so that my GUI launches independently from the establishment of the connection. However, this is not the case. When I run the program, it waits until the connection is established and then it actually runs launch(args); My concern is why is it not running independently when a new thread is being established?
public static void main(String[] args) {
initiateConnection();
launch(args);
}
private static void initiateConnection() {
new Thread(() -> {
try {
connection = new ConnectionPool("jdbc:mysql://127.0.0.0/comm", "root",
"pass");
} catch (Exception e) {
}
}).run();
}
From Javadocs of Thread.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.
So, only the body of lambda expression (which is actually body of the method run of java.lang.Runnable ) is called. It is equivalent to:
(new Runnable() {
#Override
public void run() {
try {
connection = new ConnectionPool("jdbc:mysql://127.0.0.0/comm", "root",
"pass");
} catch (Exception e) {
}
}
}).run();
You should call .start() instead of .run(). The JVM will call .run on your lambda for you.

How to create user defined Daemon thread in Java? [duplicate]

This question already has answers here:
How to create a daemon thread? and what for? [duplicate]
(4 answers)
Closed 6 years ago.
Can anyone tell me how we can create Daemon thread in Java?
I mean the syntax and how it can be used and modified.
JVM garbage collection thread is a typical Daemon Thread, and you can create daemon thread just like the normal thread and call such thread setDaemon(true) and here i make a simple demo:
/**
* Created by crabime on 11/10/16.
*/
public class DaemonTest extends Thread {
#Override
public void run() {
for (int i = 0; i < 1000; i++){
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args) {
DaemonTest d = new DaemonTest();
d.setDaemon(true);
d.start();
try {
Thread.sleep(200);//after 200 million seconds, main thread ends and no matter DaemonTest thread run to the end or not, it will stop
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Java - creating a new thread

I'm new to threads. I wanted to create some simple function working separately from main thread. But it doesn't seem to work. I'd just like to create new thread and do some stuff there independently of what's happening on main thread. This code may look weird but I don't have much experience with threading so far. Could you explain me what's wrong with this?
public static void main(String args[]){
test z=new test();
z.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.add(z);
frame.addKeyListener(z);
frame.setVisible(true);
one=new Thread(){
public void run() {
one.start();
try{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v){System.out.println(v);}
}
};
}
You are calling the one.start() method in the run method of your Thread. But the run method will only be called when a thread is already started. Do this instead:
one = new Thread() {
public void run() {
try {
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v) {
System.out.println(v);
}
}
};
one.start();
You can do like:
Thread t1 = new Thread(new Runnable() {
public void run()
{
// code goes here.
}});
t1.start();
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start().
The result is a new instance of class Thread, which is called join().
You need to do two things:
Start the thread
Wait for the thread to finish (die) before proceeding
ie
one.start();
one.join();
If you don't start() it, nothing will happen - creating a Thread doesn't execute it.
If you don't join) it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
Since a new question has just been closed against this: you shouldn't create Thread objects yourself. Here's another way to do it:
public void method() {
Executors.newSingleThreadExecutor().submit(() -> {
// yourCode
});
}
You should probably retain the executor service between calls though.
There are several ways to create a thread
by extending Thread class >5
by implementing Runnable interface - > 5
by using ExecutorService inteface - >=8
If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.
Try this, which will help you to call as many times you needed.
It will be helpful when you need to execute your run more then once and from many place.
class A extends Thread {
public void run() {
//Code you want to get executed seperately then main thread.
}
}
Main class
A obj1 = new A();
obj1.start();
A obj2 = new A();
obj2.start();
run() method is called by start(). That happens automatically. You just need to call start(). For a complete tutorial on creating and calling threads see my blog http://preciselyconcise.com/java/concurrency/a_concurrency.php
A simpler way can be :
new Thread(YourSampleClass).start();
Please try this. You will understand all perfectly after you will take a look on my solution.
There are only 2 ways of creating threads in java
with implements Runnable
class One implements Runnable {
#Override
public void run() {
System.out.println("Running thread 1 ... ");
}
with extends Thread
class Two extends Thread {
#Override
public void run() {
System.out.println("Running thread 2 ... ");
}
Your MAIN class here
public class ExampleMain {
public static void main(String[] args) {
One demo1 = new One();
Thread t1 = new Thread(demo1);
t1.start();
Two demo2 = new Two();
Thread t2 = new Thread(demo2);
t2.start();
}
}

Categories

Resources