java tutorial - java start thread - java programming - learn java - java basics - java for beginners

Learn Java - Java tutorial - Java thread start - Java examples - Java programs
Creating and Starting Threads
- To create a thread in Java is done like this:
Thread thread = new Thread();
click below button to copy the code. By - java tutorial - team
- First to start the Java thread you will call its start() method, like this:
thread.start();
click below button to copy the code. By - java tutorial - team
- This example doesn't specify any code for the thread to execute. The thread will stop again right away after it is started.
- There are two ways to specify what code the thread must execute.
- The first is to create a subclass of Thread and then override the run() method.
- The second is to pass an object which implements Runnable (java.lang.Runnable to the Thread constructor).
Can we start a thread twice ?
- No. After starting a thread, it can never be started again.
- If you did this, the IllegalThreadStateException be thrown.
- In such case, thread can run only one time however for second time, it will throw exception.
Sample Code
public class ThreadTwice extends Thread{
public void run(){
System.out.println("Welcome to Wikitechy tutorials!!!");
}
public static void main(String args[]){
ThreadTwice time1=new ThreadTwice();
time1.start();
time1.start();
}
}
click below button to copy the code. By - java tutorial - team
Output
Welcome to Wikitechy tutorials!!!
Exception in thread "main" java.lang.IllegalThreadStateException