Java - creating a new thread

JavaMultithreading

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

You can do like:

	Thread t1 = new Thread(new Runnable() {
	public void run()
	{
	     // code goes here.
	}});  
	t1.start();

Solution 3 - Java

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

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

There are several ways to create a thread

  1. by extending Thread class >5
  2. by implementing Runnable interface - > 5
  3. by using ExecutorService inteface - >=8

Solution 9 - Java

A simpler way can be :

new Thread(YourSampleClass).start();    

Solution 10 - Java

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt MartinView Question on Stackoverflow
Solution 1 - JavastinepikeView Answer on Stackoverflow
Solution 2 - JavaspiralmoonView Answer on Stackoverflow
Solution 3 - JavaМаксим КазаченкоView Answer on Stackoverflow
Solution 4 - JavaBohemianView Answer on Stackoverflow
Solution 5 - JavadaniuView Answer on Stackoverflow
Solution 6 - JavaJayeshView Answer on Stackoverflow
Solution 7 - JavaSai SunderView Answer on Stackoverflow
Solution 8 - JavaUdayView Answer on Stackoverflow
Solution 9 - JavaMehdiView Answer on Stackoverflow
Solution 10 - JavaCristian BabarusiView Answer on Stackoverflow