Threads in Java
public class Main {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread started running.");
}
}
- Interviewer: Create an empty class called MyThreadParent.
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyThread());
thread.start();
}
}
class MyThreadParent {}
class MyThread extends MyThreadParent implements Runnable {
@Override
public void run() {
System.out.println("Runnable started running.");
}
}
- Interviewer: What are commonly used Thread class methods?
You:
- isAlive(): Tests if the thread is alive.
- yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute.
- join(): Waits for a thread to die.