PPTS
PPTS
CO- 3
Thread class:
Starting a thread:
1.public class MyThread2 implements Runnable 1./ creating an object of the class Thread using T
hread(Runnable r, String name)
2.{ 2.Thread th1 = new Thread(r1, "My new thread")
3.public void run() ;
4.{ 3.
5.System.out.println("Now the thread is running4.//..."
the start() method moves the thread to the a
); ctive state
6.} 5.th1.start();
7. 6.
8.// main method 7.// getting the thread name by invoking the getN
9.public static void main(String argvs[]) ame() method
10.{ 8.String str = th1.getName();
11.// creating an object of the class MyThread29.System.out.println(str);
12.Runnable r1 = new MyThread2(); 10.}
11.}
Waiting /
Blocked
Ready /
Running
Runnable
If Thread Scheduler
.
allocates CPU
t.start() If run() method
completes
Dead /
New
t = new Terminat
MyThread() e
9/3/20XX Presentation Title 18
CREATED BY K. VICTOR BABU
public class Mythread extends Thread{ public class Demo {
public void run()
{ public static void main(String[] args) {
for(int i=1;i<=10;i++) // TODO Auto-generated method stub
Mythread t=new Mythread();
System.out.println("Child Thred"); t.start();
} for(int i=1;i<=10;i++)
System.out.println("MAIN Thred");
}
A component of Java that decides which thread to run or execute and which thread to
thread scheduler if it is in the runnable state. However, if there is more than one
thread in the runnable state, it is up to the thread scheduler to pick one of the
threads and ignore the other ones. There are some criteria that decide which thread
will execute first. There are two factors for scheduling a thread i.e. Priority and Time
of arrival.
Time of Arrival: Suppose two threads of the same priority enter the runnable
state, then priority cannot be the factor to pick a thread from these two threads. In
such a case, arrival time of thread is considered by the thread scheduler. A
thread that arrived first gets the preference over the other threads.
5. try{Thread.sleep(500);}catch(InterruptedExc
eption e){System.out.println(e);}
6. System.out.println(i);
7. }
8. }
9. public static void main(String args[]){
10. TestSleepMethod1 t1=new TestSleepMethod1(
);
11. TestSleepMethod1 t2=new TestSleepMethod1(
);
12.
13. t1.start();
14. t2.start();
15. }
16.}
CREATED BY K. VICTOR BABU
Important Points to Remember About the Sleep()
Method
If the system that is executing the threads is busy, then the actual
sleeping time of the thread is generally more as compared to the time
passed in arguments. However, if the system executing the sleep()
method has less load, then the actual sleeping time of the thread is
almost equal to the time passed in the argument.
• Custom Priority
• 1 – MIN_PRIORITY
• 10 – MAX_PRIORITY
• 5 – NORM_PRIORITY
• getPriority()
• setPriority(int level)
In Java, the yield() method is a static method of the Thread class. It's used to pause the execution of the
currently executing thread temporarily, allowing other threads of the same priority to execute
However, it's important to note that the yield() method is just a suggestion to the scheduler; it's not
guaranteed that the thread will yield the CPU.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
3.Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
4.Cooperation (Inter-thread communication in java)
Mutual Exclusive helps keep threads from interfering with one another
while sharing data. It can be achieved by using the following three ways:
In Java, mutual exclusion is typically implemented using locks. A lock is an object that can be
acquired by a thread. Once a thread has acquired a lock, no other thread can acquire it until
the first thread releases it.
If we put all the codes of the method in the synchronized block, it will work same as
the synchronized method.
Points to Remember
•A Java synchronized block doesn't allow more than one JVM, to provide access control
to a shared resource.
•The system performance may degrade because of the slower working of synchronized
keyword.
2. //code block
3.}
1.class Table
2.{
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e)
{System.out.println(e);}
10. }
11. }
12. }//end of the method
13.}
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for
an object lock, that is acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is
called deadlock.
A deadlock may also include more than two threads. The reason is that it can be
difficult to detect a deadlock. Here is an example in which four threads have
deadlocked:
Thread 1 locks A, waits for B
Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and thread 4 waits for
thread 1.
A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the resources A and
B, is the main issue. To solve the issue we will have to simply re-order the statements where the code is
accessing shared resources.
1.Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the
main reason for a deadlock condition. It normally happens when you give locks to
multiple threads.
2.Avoid Unnecessary Locks: The locks should be given to the important threads.
Giving locks to the unnecessary threads that cause the deadlock condition.
3.Using Thread Join: A deadlock usually happens when one thread is waiting for the
other to finish. In this case, we can use join with a maximum time that a thread will
take.
•wait()
•notify()
•notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
The notify() method wakes up a single thread that is waiting on this object's monitor.
Syntax:
3) notifyAll() method
The produce() method represents the producer, which continuously produces items (incrementing
integers) and adds them to the buffer. It waits if the buffer is full.
The consume() method represents the consumer, which continuously consumes items from the
buffer. It waits if the buffer is empty.
The main method initializes two threads, one for the producer and one for the consumer. They
start executing their respective methods concurrently.
Synchronization is achieved using the synchronized block, ensuring that only one thread can
access the buffer at a time.
wait() and notify() methods are used for signaling between producer and consumer threads. The
producer calls wait() when the buffer is full, and the consumer calls wait() when the buffer is
empty. They call notify() after producing or consuming an item to wake up the waiting thread.
class ProducerConsumer {
LinkedList<Integer> buffer = new LinkedList<>();
int capacity = 5;
notify();
Thread.sleep(1000);
}
}
}
notify();
Thread.sleep(1000);
}
}
}
}
A Semaphore is used to limit the number of threads that want to access a shared resource. In other
words, it is a non-negative variable that is shared among the threads known as a counter. It sets the
limit of the threads. A mechanism in which a thread is waiting on a semaphore can be signaled by
other threads.
Semaphore controls over the shared resource through a counter variable. The counter
is a non-negative value. It contains a value either greater than 0 or equal to 0.
•If counter > 0, the thread gets permission to access the shared resource and the
counter value is decremented by 1.
•When the execution of the thread is completed then there is no need for the resource
and the thread releases it. After releasing the resource, the counter
value incremented by 1.
•If another thread is waiting for acquiring a resource, the thread will acquire a permit at
that time.
•If counter = 0, the thread does not get permission to access the shared resource.
Both threads are started using the start() method. This initiates their execution.
Thread mt1 (named "A") begins execution of its run() method. Since it's the first thread to run, it will
acquire the semaphore permit first.
Thread mt1 prints that it is waiting for a permit and then successfully acquires the permit. It enters the
critical section.
Inside the critical section, thread mt1 increments Shared.count five times, printing the current value each
time. After each increment, it sleeps for 10 milliseconds to allow thread mt2 to execute.
While thread mt1 is sleeping, thread mt2 is waiting for the semaphore permit.
After completing its execution in the critical section, thread mt1 releases the semaphore permit.
Inside the critical section, thread mt2 decrements Shared.count five times, printing the current value each time.
After each decrement, it sleeps for 10 milliseconds to allow thread mt1 to execute.
After completing its execution in the critical section, thread mt2 releases the semaphore permit.
The main thread, in the ThreadSemaphoreDemo class, waits for both mt1 and mt2 to finish using the join()
method.
Finally, after both threads have finished, the main thread prints the final value of Shared.count.
This sequence ensures that only one thread can access the critical section (manipulating Shared.count) at any
given time, ensuring the safety of the shared resource.
Java provides a Semaphore class to implement the semaphore mechanism. It belongs to the
java.util.concurrent package. It implements the Serializable interface. Hence, manual
implementation is not required.
Semaphore(int permits)
Semaphore(int permits, boolean fair)
Semaphore(int permits)
It creates a Semaphore and parses the number of permits (initial number of permits available) as
an argument. It specifies the number of threads that can share a resource at a time. The value of
permits may be negative. In such a case, a release must occur before any acquires will be
granted.
Syntax:
public Semaphore(int permits)
permits: The value of permits may be negative. In such a case, the release must occur before any acquires will
be granted.
fair: If we set the value to true, the semaphore guarantees FIFO to the threads in the order they are requested,
false By default, all the threads that are waiting for the resource grants permit in an undefined order.