Java thread not sleeping - java

I have this code(FULL SOURCE CODE) :-
class thread implements Runnable {
int i=0;
Thread t;
public void main(){
t= new Thread(this); //edited
for(i=0;i<=5;i++){
System.out.println(i);
}
}
public void run(){
try{
Thread.sleep(1000); //EDITED EARLIER, was: t.sleep(1000);
}
catch(InterruptedException e){
}
}
}
The thread is supposed to sleep for 1 second. But, the thread does not sleep at all. Where am I going wrong. Any help will be appreciated.
EDIT
I get the following error now ->
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:682)
at thread.main(thread.java:7)

The fundamental issue here is that you never start the thread. Your program's main is called on the default thread, you create an instance, and then do nothing with it.
If you want to start your thread, call t.start() (once). That will start your thread, which will run alongside the default thread the JVM created when running your program. Other than that both threads are running at the same time, they don't interact in your program, so you'll still see the numbers get printed out right away. Depending on what you're trying to do, you may want to move your loop from main to run.
(And yes, sleep is a static method which makes the current thread sleep. In Java, it's syntactically valid to call a static method through an instance reference, but it's a bad idea.)
So for instance, here's your class with minimal mods (note: your environment seems to create an instance and call the instance-specific main below, which is non-standard,but I left it alone as it seems to be what your environment does):
class ThreadExample implements Runnable
{
public void main(){
Thread t= new Thread(this);
t.start();
}
public void run(){
int i;
try{
Thread.sleep(1000);
for(i=0;i<=5;i++){
System.out.println(i);
}
}
catch(InterruptedException e){
}
}
}
Changes:
Use standard Java naming conventions for the class.
Make t a local variable in main.
Actually start the thread in main.
Move loop from main to run, after the sleep call.
Make i a local variable in run.
Call sleep via Thread rather than this.
Here's a more normal example with a static main:
class ThreadExample implements Runnable
{
public static void main(String[] args) {
Thread t = new Thread(new ThreadExample());
t.start();
}
public void run(){
int i;
try{
Thread.sleep(1000);
for(i=0;i<=5;i++){
System.out.println(i);
}
}
catch(InterruptedException e){
}
}
}
Live example with debug output

The sleep method in Thread is static, so it should be called Thread.sleep() and it actually makes the currently executing thread to sleep, not a specific thread instance that you call the method on.

Your code should look more like this. It has been a while since I've worked with threads so there might be minor errors people should feel free to edit.
class myThread implements Runnable
{
public void main(){
MyThread t= new MyThread();
t.start();
t.join();
}
public void run(){
try{
for(i=0;i<=5;i++){
System.out.println(i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
}
}
}

Related

Doing things while for loop is running

I don't know how to do this, what i am trying to do is running a for loop and still can do other things like reading input from user,change files contents, etc...(you get the idea) while the loop is running, is there any way to do it?
Btw i am using java
You can create a new Thread for the task you want to do separately while the loop is running.
Thread t = new Thread(() -> {
//your code here
});
t.start();
You can do that using threads in java. Java don't support callbacks but with threads you can run multiple process at the same time. You can read more about threads in the java doc.or any java tutorial. The while loop should run on a separate thread while other things you want to do should run on another thread.
You can Do it like this:
// the Thread class
class ThreadDemo extends Thread
{
public void run()
{
try
{
//Loop code
for(int counter = 0; counter < x ;counter++){
}
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
ThreadDemo object = new ThreadDemo();
object.start();
}
}
More on Threads

run() is never called by Thread.start() method

I have written a small multithreading program.
public class NewThread implements Runnable {
Thread t;
public NewThread() {
t = new Thread(this, "Thread created by Thread Class.");
System.out.println("Created by constuctor:"+ t);
t.start(); // This will call run, because t has context as this
}
#Override
public void run() {
System.out.println("run() method called.");
}
public static void main(String[] args) {
new NewThread();
}
}
This is how the book says to write it. However, I never get the run() method called statement in the console. Thus, it seems run() is never called. How can this be true?
Edit: Yes, it is bad practice to start a Thread from constructor, but that is not affecting the question. (I am getting so many down votes for that)
run() is never called by Thread.start() method
You code actually works on my system but that it doesn't work on your's, demonstrates that you have a classic race condition.
Inside of main(), the NewThread is constructed but the Java language says that it can reorder operations so that the operations in a constructor can happen after the constructor finishes. So it is possible that main() might finish before the NewThread has actually been started which can result in the JVM shutting down without running the thread.
Because of instruction reordering, you should never have a thread auto-start itself inside of the constructor. See: Why not to start a thread in the constructor? How to terminate?
You should instead do:
public NewThread() {
t = new Thread(this, "Thread created by Thread Class.");
System.out.println("Created by constuctor:" + t);
// don't start here
}
public void start() {
// start in another method
t.start();
}
public void run() {
System.out.println("run() method called.");
}
...
public static void main(String[] args) {
NewThread nt = new NewThread();
nt.start();
}
Since the NewThread has the same daemon status as your main thread (which is non-daemon) the JVM will not shutdown until nt.run() completes.

Calling the run method in a thread

Here I have created the class Main and inside it a thread t1 had been start by sending it a runnable target. But since the thread has been started I believe the run() method, should run and call a.SetI(20) method. But the output gives as 0. Could somone please let me know the logic behind this.
public class _216 {
private int i;
public synchronized void setI(int i){
this.i=i;
}
public synchronized int getI(){
return i;
}
}
class Main{
public static void main(String[] args) {
final _216 a=new _216();
Runnable r=new Runnable(){
#Override
public void run() {
a.setI(20);
}
};
Thread t1=new Thread(r);
t1.start();
System.out.println(a.getI());
}
}
The 'logic behind this' is that the thread may not have executed yet when you do your print.
You should use t1.join() so that both main and this new thread will joined and later code will continue to print.
Here
Thread t1=new Thread(r);
t1.start();
t1.join()
System.out.println(a.getI());
You very well may be printing the result before the thread completes running.
At that point in time the threads may be running simultaneously.
Also recognize that i is never initialized until you call setI, consider hardcoding a default value.

threads and synchronization example

I am new to Java. Below is a code as an example of threads and synchronization.
public class A implements Runnable{
public synchronized void run(){
/*
some code here
*/
}
}
public class B {
public static void main(String[] args){
A obj1 = new A();
Thread t = new Thread(obj1);
A obj2 = obj1;
Thread t1 = new Thread(obj2);
t.start();
t1.start();
}
}
Now will this two threads block each other for same lock or will they get two different locks?
Thank you!!
(First, please stick to the Java coding conventions. A class name should always start with a capital letter. No exceptions.)
Only one of the threads will execute the run() method at a time.
The A.run() method is an instance method, and it is declared as synchronized. These two facts mean that it will acquire a lock on this (i.e. the instance of A) before entering the method body, and release it on exiting. In short, run() locks this.
So in your main program you are creating a single A instance and passing it as the target object for two threads. They both need to execute the run() method on the same object, and this cannot happen at the same time ... by the reasoning of the previous paragraph.
This does not necessarily mean that one thread will block the other. It is also possible that the first thread to be started will have completed its run() call before the second thread is ready to try the call. But we can say ... definitively ... that the two threads' calls to run() will NOT overlap in time.
They will block each other, since they're both synchronized on the same object.
For example, this program:
public class Foo
{
public static void main(final String... args)
{
final Runnable r =
new Runnable()
{
public synchronized void run()
{
for(int i = 0; i < 10; ++i)
{
System.out.println(i);
try
{ Thread.sleep(1000L); }
catch(final InterruptedException ie)
{ throw new RuntimeException(ie); }
}
}
};
new Thread(r).start();
new Thread(r).start();
}
}
will print 0 through 9, pausing for a second after number, and then do it again. It will not interlace the two sets of numbers.
Synchronization forces the threads to run in order (block).
Synchronization, by definition, means that a method is run "one at a time". The first thread to be executed (likely "t") will thus complete before the 2nd thread (probably "t1")'s run() method is entered.
To test the synchronization effects:
The best experiment to run will be to fill the run() method with a call to
Thread.sleep(1000);
Then run your code with, and without the "synchronized" keyword, and time the programs execution .
The output of this code is getting intermixing of thread1 and thread0
package oopd;
/**
*
* #author mani deepak
*/
public class Oopd {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Deepak d,d1;
d=new Deepak();
d1=new Deepak();
Thread t,t1;
t=new Thread(d);
t1=new Thread(d1);
t.start();
t1.start();
}
}
class Deepak implements Runnable
{
#Override
public synchronized void run()
{
String s=Thread.currentThread().getName();
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
System.out.println(s+" "+i);
}
}
}

Correct Usage of wait and notify

I have written a program to understand wait() and notify() methods. But when I run the program it hangs and nothing happens. Basically I want one thread (ThreadDemo) to complete its execution (display its output) thereafter other thread should display its output (ThreadDemo2).
As wait and notify requires the use of same object I have created common class LogicClass.
Can you please point out what is the problem in my code? I have to use these concepts in my project.
Program Link
In the code, I noted at least two problems:
Your main function does not wait for the child threads to join and so will exit. Use Thread::join.
You never call show() function that includes the notifyAll.
Pretty sure that non-daemon threads will not exit when the main thread exits.
I'd recommend using java.util.concurrent package if at all possible. It makes multithreading less error prone. You are missing for example a missed notification guard that can cause eternal waiting. If you were to use a latch it would solve that problem.
** EDIT
Sorry I should say your existing missed notification guard (value in LogicClass) can have cases where it doesn't function correctly - the while loops before the wait or notify aren't sufficient to guarantee which thread "wins the race" to the monitor.
I made a comment earlier about making the code shorter while still demonstrating the same behaviour. You can see one thread is running show, the other display
class ThreadMain {
public static void main(String[] args) {
final LogicClass lg = new LogicClass(true);
new Thread(new Runnable() {
public void run() {
System.out.println("In threadDemo run method");
lg.show(10);
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("In thread2 run method");
lg.display(5);
}
}).start();
System.out.println("Hi, in main");
}
}
class LogicClass {
boolean value;
public LogicClass(boolean value) {
this.value = value;
}
synchronized void show(int a) {
if (value) {
for (; a != 0; a--)
System.out.println("This Output should come first");
value = false;
notifyAll();
}
}
synchronized void display(int a) {
while (value) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (; a != 0; a--)
System.out.println("This should come later");
}
}

Categories