Concurrent Programming in Java: Mrs. S.S.Jamsandekar Department of Computer Science Shivaji University
Concurrent Programming in Java: Mrs. S.S.Jamsandekar Department of Computer Science Shivaji University
Concurrent Programming in Java: Mrs. S.S.Jamsandekar Department of Computer Science Shivaji University
Mrs. S.S.Jamsandekar
Department of Computer Science
Shivaji University
JAVA Threads
Concurrent Programming in Java
Two basic units of execution
processes
Threads
Processes
A process has a self-contained execution
environment.
A process generally has a complete, private set
of basic run-time resources; in particular, each
process has its own memory space.
Processes are often seen as synonymous with
programs or applications.
Java virtual machine run as a single process.
Java application can create additional processes using a
ProcessBuilder object .
JAVA Threads
Threads
Threads are sometimes called lightweight processes
Threads also provide an execution environment
Creating a new thread requires fewer resources than
creating a new process.
Thread cannot exist on its own (threads exist within a
process )
Threads share the process's resources, including
memory and open files
A thread is an independent path of execution within a
program. (collection of statements that execute in a
specific order)
Every application has at least one thread — or
several( main Thread)
JAVA Threads
Multithreaded execution is an essential feature of the
Java platform
Multithreading refers to two or more tasks executing
concurrently within a single program..
A Java program can have many threads, and these
threads can run concurrently, either asynchronously
or synchronously.
Thread Creation
There are two ways to create thread in
java;
– Implement the Runnable interface
(java.lang.Runnable)
– By Extending the Thread class
(java.lang.Thread)
Thread Class
public class Thread
extends Object
implements Runnable
XThread(){
XThread(String threadName){
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
player3.setPriority(Thread.MAX_PRIORITY);
player3.start();
player1.start();
player2.start();
}
}
class GuessNumber1 extends Thread
Join() Method
{
private int number;
public GuessNumber1( int number)
{
this.number=number; }
public void run()
{
int counter = 0;
int guess= 0;
do
{
guess = (int)(Math.random()*100+1);
System.out.println(this.getName()+ "guesses"+guess);
counter++; }
while(guess!=number);
System.out.println(" correct!" + this.getName() + "in" + counter + "guesses" );
} }
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread.....");
thread1.start();
* All four methods can be called only from within a synchronized method
class Q
{
int n;
boolean valueSet = false;
}
class Producer implements Runnable
{
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}} }