Multithreading Java
Multithreading Java
3) context switching is
3) context switching is expensive
inexpensive
multithreading in java 1
preempted by higher priority thread - lower priority
thread that does not yield the processor is preempted by
higher priority thread - preemptive multitasking
thread class
runnable interface
method meaning
main thread -
multithreading in java 2
ways to start a thread using runnable interface
class MyThread
class MyThread
implements Runnable
implements Runnable
{
{
Thread t2;
public void run()
MyThread()
{
{
t2 = new Thread(this);
}
t2.start();
}
}
public void run()
class prg
{
{
}
public static void
}
main(String[]args)
class prg
{
{
MyThread t = new
public static void
MyThread();
main(String args[])
Thread t2 = new
{
Thread(t);
MyThread t = new
t2.start();
MyThread();
}
}
}
}
multithreading in java 3
t2 = new Thread(this)
MyThread t = new creates a new Thread
MyThread() creates an object t2 and
instance of MyThread associates it with
class t which can be current instance of
used to start a new MyThread (which
thread explains use of this
keyword)
Thread t2 = new
Thread(t) - creates a t2.start() starts the
new Thread object t2 thread t2 - invokes run
and associates it with method of MyThread
MyThread instance t by instance
passing t as a
parameter to Thread() public void run :
constructor declares a method named
run which is required
t2.start() starts the to be implemented when
thread - invokes the a class implements the
run method of MyThread runnable interface -
instance t this method contains
the code to be executed
when thread is started
in main class
in main class,
MyThread t = new
MyThread() creates an
instance of MyThread
triggering constructor
and a new thread is
started
creating a thread
multithreading in java 4
then instantiate an object of type Thread from within
the class that implements runnable
class ExtendThread
{
public static void main(String[] args)
{
new NewThread();
try
multithreading in java 5
{
for(int i=5; i>0; i—)
{
System.out.println(”Main thread: “+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(”Main thread
interrupted”);
}
System.out.println(”main thread exiting”);
}
}
multithreading in java 6