59

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);}
          }
      };
  }
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Matt Martin
  • 775
  • 3
  • 9
  • 16
  • 1
    [Java Tutorials - Defining and Starting a Thread](http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html) – Anthony Accioly Jul 20 '13 at 03:44
  • 5
    I can recommend the book Java Concurrency In Practice if you are new to threads but would like to know more. It's an enjoyable book and it takes you through threads beginning with the basic concepts. – sbrattla Jul 20 '13 at 05:24

10 Answers10

111

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();
stinepike
  • 54,068
  • 14
  • 92
  • 112
29

You can do like:

    Thread t1 = new Thread(new Runnable() {
    public void run()
    {
         // code goes here.
    }});  
    t1.start();
spiralmoon
  • 3,084
  • 2
  • 25
  • 26
12

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

Sar
  • 17
  • 8
  • 3
    Welcome to Stackoverflow. Generally answers that also include an explanation will be better received. Thanks! – JoelC Dec 17 '14 at 22:30
  • Yes, the explanation here will not prevent) **The goal** was to write code to call _start()_ and _join()_ **in one place**. Parameter anonymous class is an anonymous function. 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(). – Максим Казаченко Dec 18 '14 at 00:14
  • better to add your explanation to the actual answer by editing it – Aequitas Sep 07 '15 at 04:10
8

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Starting one thread and joining it immediately is the exception rather than the rule. If we always do this, we would never have more than two threads running at a time and one of them would be waiting in the `join()`. If what you meant was more along the lines of 'join the thread at the point in the code where you need it to have its work completed' then I would agree with the recommendation. – Rob Jul 20 '13 at 04:12
  • @Rob You would not normally join a thread, but in this case he's calling it from his `main()` which then (appears to) do nothing else, so it may well exit "immediately", and when the main thread exits the JVM shuts down - all (non-daemon) threads are killed and those not yet executed will never execute. It was only recommending `join()` because of the particular situation. – Bohemian Jul 20 '13 at 04:29
3

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.

daniu
  • 14,137
  • 4
  • 32
  • 53
3

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
Uday
  • 149
  • 6
  • what are the `>5`, `- > 5` and `- >=8` ? (ps: just implementing `Runnable` doesn't create a thread yet. In fact, `Runnable` is just an interface which describes a `run()` method, which may be executed in a blocking fashion on the current thread as well.) – bvdb Apr 30 '20 at 20:03
  • Available in java version since # – Karis Oct 07 '21 at 04:23
2

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();
Jayesh
  • 6,047
  • 13
  • 49
  • 81
2

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

Sai Sunder
  • 1,001
  • 1
  • 11
  • 16
0

A simpler way can be :

new Thread(YourSampleClass).start();    
Mehdi
  • 1,340
  • 15
  • 23
0

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

}

Cristian Babarusi
  • 1,455
  • 14
  • 19
  • What demo2 is actually doing, is pretty much something like `new Thread(new Thread())` which is just silly. --> You probably wanted to do this: `Thread t2 = new Two();` – bvdb Apr 30 '20 at 20:09