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.
Related
This question already has answers here:
How to properly stop the Thread in Java?
(9 answers)
How to timeout a thread
(17 answers)
Closed 2 years ago.
so I am making a java code testing web application and I am running each code execution in a seperate thread. The problem is that sometimes tests have a time limit or the student just writes an infinite while loop. I've tried to terminate my testing thread with "best practices" such as using interrupts but I have no control over the inner workings of my compilation function so I can't just tell the thread to look if it has been interrupted or not. I'd like advice on how to handle this situation better.
Here is my bare bones example of what I want to achieve:
public class Main {
public static void main(String[] args) {
CodeExecutionThread cex = new CodeExecutionThread();
cex.start();
try {
cex.join(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread should stop at this point.");
}
}
class CodeExecutionThread extends Thread {
public CodeExecutionThread() {
}
#Override
public void run() {
infinite_operation();
}
public void infinite_operation() {
while(true) {
System.out.println("thread active");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I came accross the same problem more than once.
Probably not what you are looking for, but there is probably no better way than to use a flag inside the worker thread -- as described here for example: https://www.baeldung.com/java-thread-stop
When using a flag, there is of course a contract between the main thread and the worker -- you need to divide the infinite_operation into smaller chunks and check for the flag.
If you do not want that kind of contract or if it is not possible, consider using a process, which can be "safely" killed by OS (https://www.baeldung.com/java-process-api).
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();
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();
This question already has answers here:
Warning message "uses or overrides a deprecated API" encountered during code compilation
(2 answers)
Closed 2 years ago.
Please answer my question need help.getting error recompile with xlint. Java uses or overrides deprecated API. This is the third time am trying to post this question and still not able to post if this question get posted this time please answer my question
class a extends Thread {
public void run() {
for(int i=1;i<=5;i++) {
if(i==1) {
yield();
}
System.out.println("message from a "+i);
}
System.out.println("exit from a");
}
}
class b extends Thread {
public void run() {
for(int i=1;i<=5;i++) {
System.out.println("message from b "+i);
if(i==3)
stop();
}
System.out.println("exit from b");
}
}
class c extends Thread {
public void run () {
for(int i=1;i<=5;i++) {
System.out.println("message from c" +i);
if(i==1)
try {
sleep(1001);
}
catch(Exception e) {
}
}
System.out.println("exit from c");
}
}
class threadsmethods {
public static void main(String args []) {
System.out.println("started Thread a");
new a().start();
System.out.println("Thread b started");
new b().start();
System.out.println("Thread c started");
new c().start();
System.out.println("end of main Thread");
}
}
Thread's stop method has been deprecated and hence you see warning.
If you just want to stop thread after 3 iteration, then you should break from loop and you will come out of run method which would stop your thread automatically. Instead of using stop use something like:
if(i==3)
break;
Once loop would exit, that would make your thread exit gracefully.
In my case I just restart emulator and Everything worked out right.
I am a beginner here and started learning java programming.
I wrote a program to try threading. In one class i wrote a program to display numbers from one to 100 and in another class to display number from 999 to 100. Now in the the main i have created an object reference for both the class(r1,r2)) and created a object for thread and passed(r1,r2-object reference of my class) them as a parameter. Now the output i get is not as expected in some way i feel my second thread is not getting executed. I am not sure if there is anything wrong with my logic or the program. Any help/advice would be appreciated. My code below for reference.
Class 1:
public class Run implements Runnable {
#Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(Run.class.getName()).log(Level.SEVERE, "...", ex);
}
System.out.println(i);
}
}
}
Class 2:
public class Run2 extends Thread {
public void run2() {
for(int i=999;i>0;i--){
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(Run2.class.getName()).log(Level.SEVERE, "....", ex);
}
System.out.println(i);
}
}
}
Main class:
public class Threading {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Run r= new Run();
Thread t1=new Thread(r);
t1.start();
Run2 r2=new Run2();
Thread t2=new Thread(r2);
t2.start();
}
}
Rename Run2's method run2 to run. You're subclassing Thread, so you get a run method that doesn't do anything (actually it checks to see if it was passed in a target runnable, in which case it calls run on the target, but since the target is null it does nothing), and that's what's getting run.
Make a habit of implementing Runnable instead of extending Thread, and use the #Override annotation to catch mistakes where you think you're overriding something but you're not.
Your class Run2's method should be named run and not run2.