Threads in Java
I was today asked in an interview over the Thread concepts in Java? The Questions were...
- What is a thread?
- Why do we go for threading?
- A real time example over the threads.
- Can we create threads in Spring framework service class.
- Can flex call a thread?
I did not answer any questions apart from definition of Thread, that too I just learnt from internet.
Can anyone explain me clearly over this.
Update:
What is a difference between a thread and a normal java class. why do we need threading... can i execute business logic in threads. Can i call a different class methods in Threads.
Solution 1:
To create threads, create a new class that extends the Thread
class, and instantiate that class. The extending class must override the run
method and call the start
method to begin execution of the thread.
Inside run
, you will define the code that constitutes a new thread. It is important to understand that run
can call other methods, use other classes and declare variables just like the main thread. The only difference is that run
establishes the entry point for another, concurrent thread of execution within your program. This will end when run
returns.
Here's an example:
public class MyThread extends Thread {
private final String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
try {
for (; ; ) {
System.out.println(name);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("sleep interrupted");
}
}
public static void main(String[] args) {
Thread t1 = new MyThread("First Thread");
Thread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
You will see this on the screen:
First Thread
Second Thread
First Thread
Second Thread
First Thread
This tutorial also explains the Runnable
interface. With Spring, you could use a thread pool.
Solution 2:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU. Each part of such program is called a thread. So,
Threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
- Extending the Thread class
- Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread
class. This class overrides the run()
method available in the Thread
class. A thread begins its life inside run()
method. We create an object of our new class and call start()
method to start the execution of a thread. Start()
invokes the run()
method on the Thread
object.
class MultithreadingDemo extends Thread{
public void run() {
try { // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e){ // Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable
interface and override run()
method. Then we instantiate a Thread object and call start()
method on this object.
class MultithreadingDemo implements Runnable{
public void run() {
try { // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() +
" is running");
}
catch (Exception e) { // Throwing an exception
System.out.println ("Exception is caught");
}
}
}
class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Thread Class vs Runnable Interface
If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
Solution 3:
I can answer the first 3 since I'm not too familiar with the threading features of Spring or Flex.
A thread is an object that has its own registers and stack that can run parallel with other threads in a process (a process is a collection of threads).
You write multi-threaded code for the program to be responsive to user interactions. Think of how annoying it would be if you had to wait for your browser to finish downloading a file before you can continue browsing.
I gave an example in #2. Other examples are any programs with a GUI (the GUI has to always be responsive to user input while performing background tasks), or server type software such as a web server where you might have to respond to 1000 requests a minute. It would be better to have a separate thread for each of those responses.
Solution 4:
One key concept to clear up is that a thread is an OS scheduling object, which just happens to have a Java class that represents it (as, say, Window would in the UI sub-system). Threads are not themselves a type of class.
Solution 5:
Flex cannot directly communicate with Java threads, there would have to be some sort of messaging whether you use JMS or whatever, Flex via BlazeDS, GraniteDS, or LCDS can communicate with JMS. One thing to remember as well is that, at the moment anyway, Flash/Flex itself is single threaded, but highly asynchronous....some would say TOO asynchronous...so any use of Java threads to speed things up may not have as great an effect as you might hope for.