Dave's Brain

Browse - Programming Tips - What's the best way to make a Java thread?

Date: 2013apr30
Language: Java

Q.  What's the best way to make a Java thread?

A.  You can declare a thread a number of ways.  For a thread of non-trivial
size I prefer extending the Thread class.  Like this:

class MyWonderfulThread extends Thread { @Override public void run() { // Do what you want } } void startIt() { MyWonderfulThread thread = new MyWonderfulThread(); thread.start(); // do NOT call run() }
Compared to other ways, your run() code is indented less. And you can add a constructor with a parameter, like so:
class MyWonderfulThread extends Thread { String greeting; MyWonderfulThread(String greeting) { this.greeting = greeting; } @Override public void run() { // Do what you want System.out.println(greeting); } } void startIt() { MyWonderfulThread thread = new MyWonderfulThread("hello"); thread.start(); }
However if a thread is very small, I would do it like this:
void startIt() { (new Thread( { @Override public void run() { // Do one thing } })).start(); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.