• Embed Doc
  • Readcast
  • Collections
  • CommentGo Back
Download
 
1
Sapna Saxena, Lecturer, Chitkara University
THREAD PROGRAMMING
 Introduction
A Thread sometimes called a lightweight process (LWP), is a basic unit of CPU utilization, itcomprises a thread ID, a program counter, a register set, and a stack. It shares with other threadsbelonging to the same process its code section, data section and other system resources. A traditional(or heavyweight) process has a single thread of control. If a process has multiple threads of control, itcan do more than one task at a time.Java is one of a small number of languages that provide support at the language level for the creationand management of threads. All Java programs comprise at least a single thread of control. Even asimple Java program consisting of only a “main” method runs a single thread in the JVM. Inaddition, Java provides commands that allow the developer to create and manipulate additionalthreads of control within the program. Classes and interfaces for creating threads are part of core
 java.lang
package and the class
 java.lang.Object
, from which all Java objects descend, has methodsto support multithreaded programming. To take advantage of the powerful networking features of Java, one has to use threads and multithreaded programming in the network programs appropriately.
Address Space
Most modern operating systems can run multiple
processes
at the same time such as we might runour email client, editor and compiler all at once. Modern desktop operating system enforce aseparation between the memory areas used by these programs, so a bug in the compiler can’t crashthe editor and the email client can’t break the compiler. Each of these separate memory areas iscalled an
address space.
 
Context Switching
The operating system is responsible for scheduling the processes ad managing the address space foreach one. Switching between processes is called
context switching
and requires the operatingsystem to save the whole state of the running process. If the computer has more than one processor,the operating system could even schedule them to run simultaneously. Because the processes arecompletely independent, the system as a whole is reliable even if the individual programs are not.
Threads
A process contains one or more independent units of execution called
threads
. Threads are similar toprocesses in that they are independent flows of control, but they are also different in important ways–
 
The threads within a process run within a single address space, so the threads operate usingthe same body of code and the same body of data.
 
Because the threads are operating within a single process, the Java Virtual Machine ratherthan operating system can do the thread scheduling. This can make context switching muchmore efficient.
Example:
 //Program displaying single Thread program //ThreadTest.javaimport java.lang.*;class ThreadTest{public static void main(String[] args){Thread t = Thread.currentThread();System.out.println(“Mainthread” + t);t.setName(“Namechange”);System.out.println(“ChangedThread” +t);
 
2
Sapna Saxena, Lecturer, Chitkara University
try{for(int i=0;i>10;i++){System.out.println(i);Thread.sleep(500);}}catch(InterruptedException e) {}}}
Creating and Running a Thread
 To run more than one task concurrently, developer can make use of threads. There are two ways todo this –
 
Using a subclass of the Thread class
 When the subclass of the Thread class is created, this class should define its own
run()
 method to override the
run()
method of the Thread class. This run() method is where the task is performed.Just as the main() method is the first user defined method the Java Run Time (JRE) calls tostart an application, that run() method is the first user-defined method, the JRE calls to start athread. An instance of this subclass is then created by a new statement, followed by a call tothe thread’s start() method to have the run() method executed.
 
Implementing the Runnable interface
 The
Runnable
interface requires only one method to be implemented. Developer shouldcreate an instance of this class with a new statement, followed by the creation of a Threadinstance with another new statement, and finally a call to this thread instance’s start() methodto start performing the task defined in the run() method. A class instance with the run()method defined within it must be passed in as argument in creating the thread instance, sothat when the start() method of this thread instance is called, Java Run Time knows whichrun() method to execute.
Thread Control Methods
 
Many methods defined in the Thread class control the running of a thread. Here are some mostcommonly used methods –
 
 
start() –
Used to start the execution of the thread body defined in the run() method. Programcontrol will immediately returned to the caller and a new thread will be scheduled to executethe run() method concurrently with the caller’s thread.
 
 
stop() –
This is a deprecated method. It is used to stop the execution of thread. The thread isthen considered dead, the internal states of the thread are cleared, and the resources allocatedare reclaimed. Using this method has the potential to leave data in an inconsistent state areshould be avoided.
 
 
suspend() –
This is the depracated method. It is used to temporarily stop the execution of thethread. All the states and resources of the thread are retained. The thread can later be restartedby another thread calling the resume () method. Using this method has a strong potential fordead locks and should be avoided. Instead, we can use the object. Wait () method.
 
 
resume () –
Deprecated. It is used to resume the execution of a suspended thread. Thesuspended thread will be scheduled to run. If it has a higher priority than the running thread,the running thread will be preempted, otherwise, the just – resumed thread will wait in queue
 
3
Sapna Saxena, Lecturer, Chitkara University
for its turn to run. Using this method has a strong potential for dead locks and should beavoided.
 
sleep (long milliseconds) –
This method causes the Java run time to put the caller thread tosleep for a minimum of the specified time period. The Interrupted Exception, must be thrownwhile a thread is sleeping or any time the interrupt () method is called. Either a try – catchstatement is needed to be defined to catch the exception or the enclosing methods needs tohave this exceptions in throws clause.
 
 join () –
It is used for caller’s thread to wait for this thread to die – for example, by comingto the end of the run () method.
 
 
yield () –
A class method that temporarily stops the caller’s thread and puts it at the end of the queue to wait for another turn to be executed. It is used to make sure other thread of thesame priority have chance to run.
Thread Priorities and scheduling
 
Priorities are the way to make sure important or time – critical threads are executed frequently orimmediately.
 
Scheduling is the means to make sure priorities and fairness are enforced.If there is only one CPU, all of the runnable threads must take turns executing. Scheduling is theactivity of determining the execution order of multiple threads.Every thread in Java is assigned with a priority value, when there are more than one thread iscompeting for CPU time. Thread priority values are simple integers ranging between Threads – MIN– PRIORITY and Thread. MAX – PRIORITY. User applications are normally run with the priorityvalue of Thread . NORM – PRIORITY. The constants of Thread class – MIN – PRIORITY, NORM– PRIORITY – have the values of 1, 5 & 10 respectively.
 
When a thread is created, it will inherit the priority value of the creating thread if the priority valuedoesn’t exceed the limit important by its patent thread group. The set priority () method of Threadclass can be used to set priority value of a thread. The set Max Priority () method can be used to setthe maximum priority value of a thread group. Java’s scheduling is preemptive, i.e, if thread with ahigher priority than the currently running thread becomes runnable. The higher priority thread shouldbe executed immediately, pushing the currently running thread back to the queue to wait for its nextturn. A thread can voluntarily pass the CPU execution privilege to waiting threads of the samepriority by calling the yield () method.
 Example:
 //Program displaying Thread methods & thread Priorities //ThreadPrinting.javaimport java.lang.*;class ThreadPriorityTest.java{Int count =0;Thread t;private volatile Boolean running = true;public ThreadPriorityTest() { }public void run(){while(running){count++;}}public ThreadPriorityTest(int p){
of 00

Leave a Comment

You must be to leave a comment.
Submit
Characters: ...
You must be to leave a comment.
Submit
Characters: ...