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

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

Related

Why Iam getting Illeagal Monitor exception [duplicate]

This question already has answers here:
Java Wait and Notify: IllegalMonitorStateException
(2 answers)
Closed 4 years ago.
I am getting an illegal monitor exception. I googled it but nothing clarifies what i am doing wrong.
From this normalclass I create an object for other class and give the object to thread and synchronize the thread. Why am I getting this exception?
/* synchronize the thread object a */
/* here iam calling wait on thread as it need to complete run */
public class Normalclass
{
public static void main(String[] args)
{
NormalThread k = new NormalThread();
Thread a =new Thread(k);
a.setName("test");
a.start();
synchronized(a){
try{
a.wait();
} catch(InterruptedException e){
System.out.println("exception");
}
}
}
}
public class NormalThread implements Runnable
{
public void run()
{
for(int i=0;i<=100;i++)
{
System.out.println(i);
}
notify();
}
}
/* here iam notifying after the run for loop completed*/
// Iam getting illegal monitor exception
In your example notify() is called on NormalThread k object while wait() is called on Thread a object. You should call these methods on the same object for the signal to propagate.
You could fix your by grabbing the monitor for k to avoid the exception by using:
synchronized(this) {
notify();
}
but frankly the example makes little sense. Normally what you try to accomplish is done with Thread.join(). As per the method javadoc:
Waits for this thread to die.
Thread a = new Thread(k);
a.start();
a.join();

Multi-threaded programs in java [duplicate]

This question already has answers here:
how to override thread.start() method in java?
(11 answers)
Closed 4 years ago.
I'm new to threads in java and I'm trying to test how it works.
Unfortunately, things goes as I'm not expecting. threads seems to execute in a not-parallel way.
I've tried the sleep function but things stay the same.
The string "aa" does not printed until the thread dies !!!
What should I do?
class ThreadTest1 extends Thread {
public void start() {
for (int i=0; i<=100; i+=2) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Test {
public static void main(String[] args) throws InterruptedException {
for (int i=0; i<50; i++) {
Thread t1=new ThreadTest1();
t1.start();
System.out.println("aa");
}
}
}
Please see here for simple example: Defining and Starting a Thread
Basically - you need to implement 'run' method instead of start.
and the thread will call run after starting it with 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();

Java starting two threads? [duplicate]

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

Can't restart thread [duplicate]

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.

Categories

Resources