Multithreading in Java
Multithreading in Java
JAVA9S.com
By,
Srinivas Reddy.S
Multitasking - Multithreading
JAVA9S.com
JAVA9S.com
Execution 1 File 1
Object
Thread 4
4
3
2
Execution 2 File 2
Execution 4 File 4
Execution 3 File 3
Execution 2 File 2
Execution 1 File 1
Execution 3 File 3
Execution 4 File 4
When different tasks should be performed parallel, Multiple threads are needed
to execute code.
JAVA9S.com
Thread
A thread is like the electricity passing through the wire to the devices.
A single wire or Multi wire can power the devices to run.
JAVA9S.com
Process
JAVA9S.com
Thread
Creating Threads
Thread t = new Thread();
Thread
t.start();
To start a thread to execute the code, the start method should be invoked.
But there is no guarantee that the thread will start immediately when start is invoked.
JAVA9S.com
But the run in java.lang.Thread class has no link to Our application code.
Creating Threads
class Downloader extends Thread{
private String url;
public Downloader(String url){
this.url = url;
}
public void run(){
FileDownloader fd = new FileDownloader();
fd.download(this.url);
}
}
class FileDownload{
public File download(String url){
//code to download file
return file;
}
}
Downloader dt1 = new Downloader(xx);
Downloader dt2 = new Downloader(yy);
Downloader dt4 = new Downloader(aa);
Downloader dt3 = new Downloader(bb);
dt1
dt2
dt3
dt4
dt1.start();
dt2.start();
fd
fd
fd
fd
dt3.start();
dt4.start();
JAVA9S.com
Creating Threads
class Downloader extends Thread{
private String url;
public Downloader(String url){
this.url = url;
}
public void run(){
FileDownloader fd = new FileDownloader();
fd.download(this.url);
}
}
When you extend Thread, what you really mean is that you
are going to create a class more better or customized thread
than that is there in Java.
Do not use Thread class for Inheritance just to override
run() method.
Extending the Thread class in these type of cases is not a
good OO practice.
JAVA9S.com
import java.lang.Runnable;
class Downloader implements Runnable{
private String url;
public Downloader(String url){
this.url = url;
}
public void run(){
FileDownloader fd = new FileDownloader();
fd.download(this.url);
}
}
Runnable interface insists to override run() method which is need for a thread when it starts.
By passing a Runnable Type of object to Thread, we are directing the thread to find the run
method inside the object we have passed.
String threadName
Name that can be given for a thread
ThreadGroup group
A group into which the current
thread should be part of
Thread()
Thread(Runnable traget)
Thread(Runnable target, String name)
Thread(String name)
Thread(ThreadGroup group, Runnable Target)
Thread(ThreadGroup group, Runnable Target, String name)
Thread(ThreadGroup group, Runnable Target, String name, long stackSize)
Thread(ThreadGroup group, String name)
JAVA9S.com
JAVA9S.com
www.JAVA9S.com
Srinivas.java9s@gmail.com
facebook.com/java9s
@java9s
JAVA9s
JAVA9S.com