170.
Answer:
The following code creates a thread by implementing the
“Runnable” interface:
class MyThread implements Runnable {
public static void main(String argument[]) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread); //Line 1
thread.start(); // Line 2
}
public void run() {
System.out.println(“Inside Run Method..”);
}
}
The code above defines a class called MyThread that
implements the Runnable interface.
A new Thread object is
created and the Runnable implementation that is MyThread
instance is passed to it at line 1. When Line 2 is executed, a new
thread is spawned. This executes the
code specified within the
run() method.
Is it possible to create more than one thread in a Java
application? If so, how will the threads communicate with
each other?
Answer:
Yes, it is possible to create more
than one thread in a Java
application. For two threads to communicate with each other, the
methods wait(), notify() and notifyAll() from the object
class need to be used.