The document discusses threads and threading in Java. It covers:
- Threads allow multitasking by running multiple threads concurrently within a program.
- Threads can be created by extending the Thread class or implementing the Runnable interface.
- Threads have different states like new, ready, running, blocked, and dead. Methods like start(), sleep(), join(), yield(), etc. change a thread's state.
- Synchronization is needed to prevent data corruption when multiple threads access shared resources concurrently.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
JAVA CERTIFICATION EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
4.1 Write code to define, instantiate, and start new threads
using both java.lang.Thread and java.lang.Runnable.
4.2 Recognize the states in which a thread can exist, and
identify ways in which a thread can transition from one state
to another.
4.3 Given a scenario, write code that makes appropriate use
of object locking to protect static or instance variables from
concurrent access problems.
4.4 Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
JAVA CERTIFICATION EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
4.1 Write code to define, instantiate, and start new threads
using both java.lang.Thread and java.lang.Runnable.
4.2 Recognize the states in which a thread can exist, and
identify ways in which a thread can transition from one state
to another.
4.3 Given a scenario, write code that makes appropriate use
of object locking to protect static or instance variables from
concurrent access problems.
4.4 Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
3. 3
*
*Thread: single sequential flow of control within
a program
*Single-threaded program can handle one task
at any time.
*Multitasking allows single processor to run
several concurrent threads.
*Most modern operating systems support
multitasking.
4. 4
*
*Reactive systems – constantly monitoring
*More responsive to user input – GUI application can
interrupt a time-consuming task
*Server can handle multiple clients simultaneously
*Can take advantage of parallel processing
*Different processes do not share memory space.
*A thread can execute concurrently with other threads
within a single process.
*All threads managed by the JVM share memory space and
can communicate with each other.
7. 7
*
Creating threads in Java:
*Extend java.lang.Thread class
*run() method must be overridden (similar to main method of
sequential program)
*run() is called when execution of the thread begins
*A thread terminates when run() returns
*start() method invokes run()
*Calling run() does not create a new thread
*Implement java.lang.Runnable interface
*If already inheriting another class (i.e., JApplet)
*Single method: public void run()
*Thread class implements Runnable.
9. 9
*
A thread becomes Not Runnable when one of
these events occurs:
* Its sleep method is invoked.
* The thread calls the wait method to wait for a
specific condition to be satisfied.
* The thread is blocked by I/O.
10. 10
*
java.lang.Thread
+Thread()
+Thread(task: Runnable)
+start(): void
+isAlive(): boolean
+setPriority(p: int): void
+join(): void
+sleep(millis: long): void
+yield(): void
+interrupt(): void
Creates a default thread.
Creates a thread for a specified task.
Starts the thread that causes the run() method to be invoked by the JVM.
Tests whether the thread is currently running.
Sets priority p (ranging from 1 to 10) for this thread.
Waits for this thread to finish.
Puts the runnable object to sleep for a specified time in milliseconds.
Causes this thread to temporarily pause and allow other threads to execute.
Interrupts this thread.
«interface»
java.lang.Runnable
11. Method Meaning
*getName Obtain a thread’s name.
*getPriority Obtain a thread’s priority.
*isAlive Determine if a thread is still
running.
*join Wait for a thread to terminate.
*run Entry point for the thread.
*sleep Suspend a thread for a period of
time.
*Start Start a thread by calling its run
method.
12. The Main Thread
When a Java program starts up, one thread begins running
immediately. This is usually called the main thread of your
program, because it is the one that is executed when your
program begins.
The main thread is important for two reasons:
It is the thread from which other “child” threads will be
spawned.
Often, it must be the last thread to finish execution
because it performs various shutdown actions.
Although the main thread is created automatically when your
program is started, it can be controlled through a Thread
object. This can be done by calling the method
currentThread( ), which is a public static member of
Thread. Its general form is
static Thread currentThread( )
This method returns a reference to the thread in which it is
called.
13. 13
*
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}}}
15. 15
*
New Ready
Thread created
Finished
Running
start()
run()
Wait fortarget
tofinish
join()
run()returns
yield(), or
timeout
interrupt()
Wait fortime
out
Wait tobe
notified
sleep()
wait()
Target
finished
notify()or
notifyAll()
Timeout
Blocked
Interrupted()
A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.
16. 16
*
You can use the yield() method to temporarily release time for
other threads.
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
Thread.yield();
}
}
Every time a number is printed, the print100 thread is yielded. So,
the numbers are printed after the characters.
17. 17
*
The sleep(long mills) method puts the thread to sleep
for the specified time in milliseconds.
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex) {
}
}
}
Every time a number (>= 50) is printed, the print100
thread is put to sleep for 1 millisecond.
18. 18
*
You can use the join() method to force one thread to
wait for another thread to finish.
The numbers after 50 are printed after thread printA is finished.
printA.join()
-char token
+getToken
+setToken
+paintCompone
t
+mouseClicked
Thread
print100
-char token
+getToken
+setToken
+paintCompo
net
+mouseClicke
d
Wait for printA
to finish
+getToken
+setToken
+paintComponet
Thread
printA
-char token
+getToken
+setToken
+paintCompo
net
+mouseClicke
d
printA finished
-char token
public void run() {
Thread thread4 = new Thread(
new PrintChar('c', 40));
thread4.start();
try {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
if (i == 50) thread4.join();
}
}
catch (InterruptedException ex) {
}
}
19. 19
*
isAlive()
• method used to find out the state of a thread.
• returns true: thread is in the Ready, Blocked, or
Running state
• returns false: thread is new and has not started or if it
is finished.
interrupt()
f a thread is currently in the Ready or Running state, its
interrupted flag is set; if a thread is currently blocked,
it is awakened and enters the Ready state, and an
java.io.InterruptedException is thrown.
The isInterrupt() method tests whether the thread is
interrupted.
20. 20
*
NOTE: The Thread class also contains the stop(), suspend(),
and resume() methods. As of Java 2, these methods are
deprecated (or outdated) because they are known to be
inherently unsafe. You should assign null to a Thread variable
to indicate that it is stopped rather than use the stop()
method.
21. 21
*
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500) ;} }
22. 22
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
} } catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
} System.out.println("Main thread exiting.");
} }
23. 23
*
• Each thread is assigned a default priority of
Thread.NORM_PRIORITY (constant of 5). You
can reset the priority using setPriority(int
priority).
• Some constants for priorities include
Thread.MIN_PRIORITY
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
• By default, a thread has the priority level of the
thread that created it.
24. 24
// Demonstrate thread priorities.
class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
} }
public void stop() {
running = false;
}
public void start() {
t.start(); } }
25. 25
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
27. 27
*
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name +"Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}System.out.println("Main thread exiting.");
}}
28. *
*Synchronization is prevent data corruption
*Synchronization allows only one thread to
perform an operation on a object at a time.
*If multiple threads require an access to an
object, synchronization helps in maintaining
consistency.
*A shared resource may be corrupted if it is
accessed simultaneously by multiple threads.
29. *
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
*In this example, the counter tells how many access has been made.
*If a thread is accessing setCount and updating count and another
thread is accessing getCount at the same time, there will be
inconsistency in the value of count.
30. *
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
*By adding the synchronized keyword we make sure that when one thread is in
the setCount method the other threads are all in waiting state.
*The synchronized keyword places a lock on the object, and hence locks all the
other methods which have the keyword synchronized. The lock does not lock
the methods without the keyword synchronized and hence they are open to
access by other threads.
31. 31
*
•Conditions can be used for communication among threads.
•A thread can specify what to do under a certain condition.
•newCondition() method of Lock object.
•Condition methods:
•await() current thread waits until the condition is signaled
•signal() wakes up a waiting thread
•signalAll() wakes all waiting threads
«interface»
java.util.concurrent.Condition
+await(): void
+signal(): void
+signalAll(): Condition
Causes the current thread to
wait until the condition is
signaled.
Wakes up one waiting
thread.
Wakes up all waiting threads.
32. 32
*
Use the wait(), notify(), and notifyAll() methods to facilitate
communication among threads.
The wait(), notify(), and notifyAll() methods must be called in
a synchronized method or a synchronized block on the calling
object of these methods. Otherwise, an
IllegalMonitorStateException would occur.
The wait() method lets the thread wait until some condition
occurs. When it occurs, you can use the notify() or notifyAll()
methods to notify the waiting threads to resume normal
execution. The notifyAll() method wakes up all waiting
threads, while notify() picks up only one thread from a
waiting queue.