Download presentation
Presentation is loading. Please wait.
Published byDinah Robinson Modified over 9 years ago
1
© Wang Bin 2004 Java Threads
2
© Wang Bin 2004 In this lesson, you will learn to: u 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 u Display the current date and time on an applet Objectives
3
© Wang Bin 2004 u 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 Threads
4
© Wang Bin 2004 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 Definition of Multithreading
5
© Wang Bin 2004 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. Problem Statement
6
© Wang Bin 2004 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 extends Thread Identify the mechanism to be used for displaying the date and time
7
© Wang Bin 2004 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 extends implements Runnable Identify the mechanism...(Contd.)
8
© Wang Bin 2004 u 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 Identify the mechanism...(Contd.)
9
© Wang Bin 2004 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 Identify the mechanism...(Contd.)
10
© Wang Bin 2004 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); Identify the mechanism...(Contd.)
11
© Wang Bin 2004 Fields in the Calendar Class: FieldsReturn 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 Identify the mechanism...(Contd.)
12
© Wang Bin 2004 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 Identify the mechanism...(Contd.)
13
© Wang Bin 2004 Syntax of the setTime() method: setTime(Date date); u 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 Identify the mechanism...(Contd.)
14
© Wang Bin 2004 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 } …… } Codes
15
© Wang Bin 2004 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 Codes
16
© Wang Bin 2004 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 Codes
17
© Wang Bin 2004 u When two threads share data, we must guarantee one thread can not change data which another thread use. u We use keyword synchronized to resolve it. Thread Synchronization
18
© Wang Bin 2004 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); } Examples
19
© Wang Bin 2004 void waiting() { try { sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } Examples (Contd.)
20
© Wang Bin 2004 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]); } Examples (Contd.)
21
© Wang Bin 2004 class ThreadSync { public static void main(String args[]) { MyThread thread1 = new MyThread("Thread 1 : "); MyThread thread2 = new MyThread("Thread 2 : "); thread1.start(); thread2.start(); } Examples (Contd.)
22
© Wang Bin 2004 Result
23
© Wang Bin 2004 If no synchronized, Result:
24
© Wang Bin 2004 u 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 Summary
25
© Wang Bin 2004 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 Summary (Contd.)
26
© Wang Bin 2004 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 Summary (Contd.)
27
© Wang Bin 2004 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 Summary (Contd.)
28
© Wang Bin 2004 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 Summary (Contd.)
29
© Wang Bin 2004 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 Summary (Contd.)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.