In this chapter we will see, what are different constructors and methods present in Thread class. We have already seen Runnable interface in previous chapter which has only one method declaration – run()
Thread class constructors
2. | Thread t = new Thread(); |
3. | Thread t = new Thread(Runnable r); |
4. | Thread t = new Thread(String name); |
5. | Thread t = new Thread(Runnable r, String name); |
6. | Thread t = new Thread(ThreadGroup g, String name); |
6. | Thread t = new Thread(ThreadGroup g, Runnable r); |
7. | Thread t = new Thread(ThreadGroup g, Runnable r, String name); |
8. | Thread t = new Thread(ThreadGroup g, Runnable r, String name, long stacksize); |
Runnable r | target Runnable class (as explained in previous chapter) |
String name | Name for new Thread that will be created using this object |
ThreadGroup g | Group which will be assigned to new Thread that will be created using this object |
long stacksize | Size of JVM Thread stack |
Important Thread class methods other than start()
Every thread in java has some name, it may be default name generated by JVM or customized name provided by programmer.
We can get and set names of Thread by using following two methods:
- public final String getName()
- public final void setName()
Here is the sample example which uses common Thread methods.
You can check compilation and execution here: jDoodle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class ThreadClassMethodsDemo { public static void main(String args[]) { // Default thread String threadName = Thread.currentThread().getName(); System.out.println("Main method thread name : " + threadName); // new thread MyThread t = new MyThread(); threadName = t.getName(); System.out.println("New thread name : " + threadName); // set name of Thread Thread.currentThread().setName("webencyclop"); threadName = Thread.currentThread().getName(); System.out.println("Main method thread name now : " + threadName); } } class MyThread extends Thread { public void run() { System.out.println("Child Thread"); } } |