I was today asked in an interview over the Thread concepts in Java? The Questions were...
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.
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.
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.
Ok to answer what is thread in java in simple word its a program/piece of code which works simultaneously with your normal class. A difference between a normal class and a thread is that a thread works simultaneously its works parallely along with the normal class. In more simpler terms lets see a example where i am currently in main function and requires a function to compute something . so if that function is not in a thread then the function will be evaluated first and after then i will return to main function on the other hand if it is a thread then the function will compute and main will will also compute its next instruction.
Now as to how a thread is created
1. extend thread class: extend thread class and write start()
its a function call it using an object of current class and write a function namely void run()
and in this function write the code which needs to be performed concurrently.
Each object of the class which extends thread is a customized thread.by default every thread is inactive and to activate or call that thread just write start()
this will automatically call run which contains your code.
class MyThreads extends Thread
{
int ch ;
MyThreads(int p)
{
ch = p;
start();//statement to activate thread and call run
}
public void run()
{
if(ch == 1)
functionx()
else if(ch == 2)
functiony();
}
void fx1()
{
//parallel running code here
}
void fx2()
{
//parallel running code here
}
public static void main(String args[])
{
MyThreads obj1 = new MyThreads(1);
My3Threads obj2 = new MyThreads(2);
//mains next instruction code here
}
}
Runnable
but as this is a interface which is compatible with the current class so calling start will call the function run()
which is written in interface but as to call our run()
function call the start with a thread object like this Thread t=new thread(this); t.start();
Now to why do we go for thread,this is just like asking why do we go for multicore processor you get what I am saying, multi threading is used to execute task concurrently
A real time example would be a server any server ,consider the server of Gmail.So if g mail server was not written using multi threading then i could not log in without you logging out which means in the whole world only one person can login at one time you see how impractical it is.
http://learningsolo.com/multithreading/
Multithreading is the process of executing two or more threads concurrently in a single program. Single core processor can execute one thread at a time but OS uses the time slicing feature to share processor time. Thread is a light weight process. The thread exists in the process and requires less resources to create. It shares the process resources. When the java application starts, it creates the first user thread for main which in turn spawn’s multiple user threads and daemon thread. The thread scheduler schedules the thread execution. When the work of all the threads are done, the JVM terminates the application.
Every java application has at least one thread – main thread. Although, there are so many other java threads running in background like memory management, system management, signal processing etc. But from application point of view – main is the first java thread and we can create multiple threads from it.
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 :
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.