Transcript Threads

Java Threads
© Wang Bin 2004
Objectives
In this lesson, you will learn to:
 Define the concepts of threads and multithreading
 Identify the functions and syntax of the Thread,
Date, Calendar, and GregorianCalendar classes
and the methods used to manipulate them
 Display the current date and time on an applet
© Wang Bin 2004
Threads
 Definition of a Thread:
 A process is divided into several tasks. Each task is divided into
smaller units called threads
 A thread can be defined as a single sequential flow of control
within a program
 Every program has at least one thread that is called the
primary thread
 The microprocessor allocates memory to the processes that
you execute. Each process occupies its own address space
(memory)
 All the threads in a process share the same address space
© Wang Bin 2004
Definition of Multithreading
 A process that is made of only one thread is said to be
single-threaded
 A process having more than one thread is said to be
multithreaded. The multiple threads in the process run
at the same time, perform different tasks, and interact
with each other
 Java has built-in support for threads. A major portion
of the Java architecture is multithreaded
© Wang Bin 2004
Problem Statement
An additional feature has to be added to the
Customer details applet. The current date and time
has to be displayed on the status bar of the applet.
Write the code.
© Wang Bin 2004
Identify the mechanism to be used for displaying
the date and time
 The Thread Class:
 The java.lang.Thread class is used to construct and
access the individual threads in a multithreaded
application
 You can make your applications and classes run in
separate threads by extending the Thread class
 Syntax:
•
public class <class_name> extends Thread
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 The Runnable Interface:
 When a program needs to inherit from another class
besides the Thread class, you need to implement the
Runnable interface
 The Runnable interface consists of a single method
run(), which is executed when the thread is activated
 Syntax for implementing the Runnable interface
•
public class <class_name> extends
<superclass_name> implements Runnable
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 Life Cycle of a Thread:
 When an instance of the Thread class is created, a
thread enters the new thread state
 When the start() method of the thread is invoked,
the thread enters the runnable state
 A thread is said to be in the not runnable state if it is
sleeping, waiting, or being blocked by another thread
 A thread is put into the sleeping mode with the sleep()
method
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 Syntax of the sleep() method:
•
sleep(long t);
 In the syntax, t is the number of milliseconds for which
the thread is inactive
 A thread object is dead if the loop in run() method is
complete or a null value is assigned to the thread
 The Date Class
 The Date class encapsulates the system date and time
information
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 The Calendar Class:
 The Calendar class implements the methods that were
present in the earlier version of the Date class
 The get() Method:
 The get() method of the Calendar class is used to
extract the date, the month, or the year from a given
date
 Syntax of the get() method:
• String get(int field);
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 Fields in the Calendar Class:
Fields
Return Values
static int HOUR
Hour of the time
static int MINUTE
Minutes of the time
static int SECOND
Seconds of the time
static int DATE
Date portion of the date
static int MONTH
Month portion of the date
static int YEAR
Year portion of the date
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 The GregorianCalendar Class:
 The GregorianCalendar class is extended from the
Calendar class
 It supports calendar operations for most parts of the
world
 The setTime() Method:
 The setTime() method takes a Date object as an
argument
 It updates the GregorianCalendar object with the
current date
© Wang Bin 2004
Identify the mechanism ...(Contd.)
 Syntax of the setTime() method:
•
setTime(Date date);
 Result:
 The applet will need to show the date and time
simultaneously with the other controls, therefore use
the following:
• Thread class
• Runnable interface
• Date class
• Calendar class
• GregorianCalendar class
© Wang Bin 2004
Codes
public class CustomerApplet extends JApplet implements Runnable
{
Thread datimeThread;
Date date;
GregorianCalendar calendar;
String strDate, strTime, strStatus;
}
public void init()
{
createAppletContent(); //Method for Applet Layout is called
}
protected void createAppletContent()
{
candidateDetail(); // contents of the applet
}
public void candidateDetail()
{
datimeThread = new Thread(this);
//Initialize thread
datimeThread.start(); //Starting thread
}
……
© Wang Bin 2004
Codes
public void run()
// body of the thread
{
while(datimeThread != null)
{
display() ;
// This method displays date
try
{
datimeThread.sleep(1000);
}
catch(InterruptedException e)
{
showStatus("Thread interrupted");
}
} //end of while loop
} //end of run method
© Wang Bin 2004
Codes
public void display()
//displays date and time on the status bar
{
date = new Date();
calendar = new GregorianCalendar();
calendar.setTime(date);
strTime = calendar.get(Calendar.HOUR)+":" +
calendar.get(Calendar.MINUTE)+":"+
calendar.get(Calendar.SECOND);
strDate = calendar.get(Calendar.MONTH)+"/"+
calendar.get(Calendar.DATE)+"/"+
calendar.get(Calendar.YEAR);
strStatus=strTime+"
"+strDate;
showStatus(strStatus);
}
}//end of program
© Wang Bin 2004
Thread Synchronization
 When two threads share data, we must
guarantee one thread can not change data
which another thread use.
 We use keyword synchronized to resolve it.
© Wang Bin 2004
Examples
class MyThread extends Thread
{
static String message[] =
{"I", "Love","Java","Very","Much."};
public MyThread(String id)
{
super(id);
}
public void run()
{
Sync.displayList(getName(), message);
}
© Wang Bin 2004
Examples (Contd.)
void waiting()
{
try
{
sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
© Wang Bin 2004
Examples (Contd.)
class Sync
{
public static synchronized void displayList(String name,
String list[])
{
for(int i = 0; i < list.length; ++i)
{
MyThread thread
= (MyThread)Thread.currentThread();
thread.waiting();
System.out.println(name + list[i]);
}
}
}
© Wang Bin 2004
Examples (Contd.)
class ThreadSync
{
public static void main(String args[])
{
MyThread thread1
= new MyThread("Thread 1 : ");
MyThread thread2
= new MyThread("Thread 2 : ");
thread1.start();
thread2.start();
}
}
© Wang Bin 2004
Result
© Wang Bin 2004
If no synchronized, Result:
© Wang Bin 2004
Summary
 In this lesson, you learned that:
 You can execute multiple tasks within a program using
threads
 A thread, like a program, has a beginning, a sequence of
steps, and an end. However, it is not a program on its
own but runs within a process of a program. A process is
an executing instance of a program. A thread is also
known as a lightweight process or the execution context
 A process having more than one thread is said to be
multithreaded. The multiple threads in a process run
simultaneously, perform different tasks, and interact
with each other
© Wang Bin 2004
Summary (Contd.)
 The java.lang.Thread class is used to construct and
access the individual threads in a multithreaded
application
 Applets extend from the JApplet class. Since Java
does not support multiple inheritance, you cannot inherit
a class from the JApplet as well as the Thread class.
Java provides the Runnable interface to solve this
problem. The Runnable interface consists of a single
method run(), which is executed when the thread is
activated
© Wang Bin 2004
Summary (Contd.)
 The life cycle of a thread consists of four stages:
•
New thread
•
Not Runnable
•
Runnable
•
Dead
 When an instance of the Thread class is created, the
thread enters the new thread state
 The start() method is responsible for starting a
thread. When the start() method of the thread is
invoked, the thread enters the runnable state
© Wang Bin 2004
Summary (Contd.)
 The activities to be performed by a thread are coded in
the run() method
 A thread is said to be in the not runnable state if it:
•
Is sleeping,
•
Is waiting, or
•
Is being blocked by another thread
 A thread is put into the sleeping mode with the sleep()
method
© Wang Bin 2004
Summary (Contd.)
 Invoking the stop() method of an applet kills a thread.
The isAlive() method of the Thread class is used to
determine whether a thread has been started or
stopped
 The Date class is responsible for encapsulating the
date and time
 The Calendar class implements the date methods that
were present earlier in the Date class
 The GregorianCalendar class is extended from the
Calendar class. It supports calendar operations for
most parts of the world
© Wang Bin 2004
Summary (Contd.)
 The setTime() method sets the calendar's current
time with the given date
 The get() method is used to extract the date, month,
and year from the Calendar variable
 The showStatus() method displays a message on the
status bar
 Thread Synchronization
 Keyword synchronized
© Wang Bin 2004