Click here to download eclipse supported ZIP file
Java is amulti threaded programming language which means we can develop multi threaded program using Java. A multi threaded program contains two or more parts that can run concurrently and each part can handle different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources such as a CPU. Multi threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.
Multi threading enables you to write in a way where multiple activities can proceed concurrently in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
Above-mentioned stages are explained here:
New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
Terminated ( Dead ): A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent.
Create Thread by Implementing Runnable Interface:
If your class is intended to be executed as a thread then you can achieve this by implementing Runnable interface. You will need to follow three basic steps:
Step 1:
As a first step you need to implement a run() method provided by Runnable interface. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method:
public void run( )
Step 2:
At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Step 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
} |
package com.cv.java.multithread;
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
} |
This would produce the following result:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method:
public void run( )
Step 2
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is the preceding program rewritten to extend Thread:
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class TestThread2 {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
|
This would produce the following result:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread Methods:
Following is the list of important methods available in the Thread class.
SN |
Methods with Description |
1 |
public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
|
2 |
public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. |
3 |
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
|
4 |
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
|
5 |
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
|
6 |
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the
second thread terminates or the specified number of milliseconds passes.
|
7 |
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
|
8 |
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.
|
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
SN |
Methods with Description |
1 |
public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
|
2 |
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds.
|
3 |
public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
|
4 |
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
|
5 | public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded
application.
|
Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
} |
Following is another class which extends Thread class:
// File Name : GuessANumber.java
// Create a thread to extentd Thread
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(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.**");
}
} |
Following is the main program which makes use of above defined classes:
// File Name : ThreadClassDemo.java
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadClassDemo {
public static void main(String[] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
} |
This would produce the following result. You can try this example again and again and you would get different result every time.
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
Major Java Multithreading Concepts:
While doing Multithreading programming in Java, you would need to have the following concepts very handy:
package com.cv.java.multithread;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Chandra Vardhan
*
*/
public class A {
private static final List<String> list = new ArrayList<String>();
private static final String name = "chote";
private static final Map<String,String> map = new HashMap<String,String>();
public synchronized void foo(B b) {
System.out.println("thread1 started execution of foo()");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("thread1 is trying to call b's last() ");
b.last();
}
public synchronized void last() {
System.out.println("this is last() in A class");
}
public static void main(String[] args) {
list.add("chote");
list.add("pappy");
List<String> tempList= new ArrayList<String>();
tempList.add("vardhan");
tempList.add("kodam");
//list.addAll(tempList);
//list = tempList;
//name = "Shravya";
//name = "cv";
map.put("name", "chote");
map.put("name1", "pappy");
Map<String,String> map2 = new HashMap<String,String>();
//map = map2;
System.out.println(list);
System.out.println(map);
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class AlphabetPrinter {
public static void main(String[] args) throws InterruptedException {
NumberPrinter np = new NumberPrinter();
np.start();
synchronized (np) {
for (int i = 65; i <=90; i++) {
System.out.println((char)i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
np.wait();
np.notify();
}
}
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class B {
public synchronized void bar(A a) {
System.out.println("thread2 started execution of bar()");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("thread2 is trying to call A's last()");
a.last();
}
public synchronized void last() {
System.out.println("this is last() in b class");
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class DeadLockDemo {
/**
* @param args
*/
public static void main(String[] args) {
new MyThread().start();
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class IllegalThreadStateExceptionTest {
/**
* @param args
*/
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();//means do not start same thread two times...
;;;
thread.start();//RuntimeExp:java.lang.IllegalThreadStateException
}
} |
package com.cv.java.multithread;
public class MyThread extends Thread {
A a = new A();
B b = new B();
public void m1() {
Thread t = new Thread();
t.start();
a.foo(b);
}
public void run() {
b.bar(a);
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class MyThread2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getPriority());
System.out.println("child thread running here..." + i);
}
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class MyThreadGroup extends Thread {
MyThreadGroup(ThreadGroup tg, String name) {
super(tg, name);
}
public void run() {
System.out.println("child thread");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class NumberPrinter {
public void run() {
synchronized(this)
{
for(int i=65;i<=90;i++)
{
System.out.println(i+" ");
this.notify();
try {
Thread.sleep(2000);
if(i<90)
{
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void start() {
run();
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class PriorityTest {
/**
* @param args
*/
public static void main(String[] args) {
MyThread2 myThread = new MyThread2();
Thread thread = new Thread(myThread);
thread.setPriority(1);// accepted...
Thread.currentThread().setPriority(10);
thread.setDaemon(true);// we can set deamon nature after starting
// of thread.
thread.start();
// thread.setDaemon(true);// we can NOT set deamon nature after starting
// of thread.
System.out.println(Thread.currentThread().getPriority());
for (int i = 0; i < 5; i++) {
System.out.println("Am from main thread===" + i);
}
// Thread.currentThread().setDaemon(true);// we can not set deamon nature after starting
// of thread.
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
} |
package com.cv.java.multithread;
public class RunnableImpl implements Runnable {
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println("run method");
}
}
} |
package com.cv.java.multithread;
public class RunnableTest {
public static void main(String[] args) {
RunnableImpl r = new RunnableImpl();
Thread t = new Thread(r);
t.start();
r.run();
for (int i = 1; i < 10; i++) {
System.out.println("main method");
}
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadGroupDemo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getThreadGroup().getParent()
.getName());
System.out.println(Thread.currentThread().getThreadGroup().getName());
ThreadGroup pg = new ThreadGroup("First group");
ThreadGroup cg = new ThreadGroup(pg, "secound group");
System.out.println(cg);
MyThreadGroup t1 = new MyThreadGroup(pg, "childThread1");
MyThreadGroup t2 = new MyThreadGroup(pg, "childThread2");
t1.start();
t2.start();
System.out.println(pg.activeCount());
System.out.println(pg.activeGroupCount());
pg.list();
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadGroupTest {
public static void main(String[] args) {
ThreadGroup tg = new ThreadGroup("sv");
Thread t = new Thread(tg, "cv");
System.out.println(Thread.currentThread().getName());
System.out.println(t);
System.out.println(tg);
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadJoin extends Thread {
static Thread wt;
public void run() {
for (int i = 0; i < 10; i++) {
try {
wt.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("child method");
}
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadJoinTest {
/**
* Sheriff
*
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ThreadJoin.wt = Thread.currentThread();
ThreadJoin t = new ThreadJoin();
t.start();
for (int i = 0; i < 5; i++) {
System.out.println("main method");
}
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadJoinYieldTest {
/**
* Sheriff
*
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().setPriority(9);
System.out.println(Thread.currentThread().getName());
ThreadJoin t = new ThreadJoin();
t.start();
Thread.yield();
System.out.println(t.getName());
for (int i = 0; i < 10; i++) {
System.out.println("main thread");
}
}
} |
/**
*
*/
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadNameTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
MyThread2 myThread = new MyThread2();
Thread thread = new Thread(myThread);
System.out.println(thread.getName());
thread.start();
thread.setName("good");
System.out.println(thread.getName());
System.out.println("main... thread...");
}
} |
package com.cv.java.multithread;
/**
* @author Chandra Vardhan
*
*/
public class ThreadPriority {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("default thread priority is====="
+ Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("default thread priority is====="
+ Thread.currentThread().getPriority());
MyThread2 myThread = new MyThread2();
Thread thread = new Thread(myThread);
thread.setPriority(10);//accepted...
thread.setPriority(1);//accepted...we can set thread priority more than once...
//thread.setPriority(11);//below 1 and after 10 then we will get Exception like
// java.lang.IllegalArgumentExceptio
thread.start();
// Thread.currentThread().setDaemon(true);
// thread.setDaemon(true); we can not set deamon nature after starting of thread.
}
} |
package com.cv.java.multithreading;
/**
* @author Chandra Vardhan
*
*/
public class EvenPrintThread extends Thread {
Table t;
public EvenPrintThread() {
}
EvenPrintThread(Table t) {
this.t = t;
}
public void run() {
try {
Thread.sleep(400);
} catch (Exception e) {
}
Table.evenPrint();
}
} |
package com.cv.java.multithreading;
/**
* @author Chandra Vardhan
*
*/
public class OddPrintThread extends Thread {
Table t;
public OddPrintThread() {
}
OddPrintThread(Table t) {
this.t = t;
}
public void run() {
try {
Thread.sleep(400);
} catch (Exception e) {
}
t.oddPrint();
}
} |
package com.cv.java.multithreading;
/**
* @author Chandra Vardhan
*
*/
public class Table {
private int n;
private static int n1;
public Table() {
}
public Table(int n) {
this.n1 = n;
this.n = n;
}
private static Table CLASS_LOCK = new Table();
public static synchronized void printSync1(int n) {
System.out.println("printcSync1 === object lock...");
for (int i = 1; i <= 2; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static synchronized void printSync2(int n) {
System.out.println("printcSync2 === object lock...");
for (int i = 1; i <= 2; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static void printStatic(int n) {
System.out.println("printStatic === NO NO lock...");
for (int i = 1; i <= 2; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static void printStaticSync(int n) {
System.out.println("printStaticSync === Static lock...");
synchronized (CLASS_LOCK) {
for (int i = 1; i <= 2; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
public synchronized void print(int n) {
System.out.println("print === No lock...");
for (int i = 1; i <= 2; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static synchronized void evenPrint() {
// System.out.println("print === No lock...");
for (int i = 1; i <= n1; i++) {
if (i % 2 == 0) {
try {
Thread.sleep(400);
} catch (Exception e) {
//System.out.println(e);
}
System.out.println(i);
}
}
}
public synchronized void oddPrint() {
// System.out.println("print === No lock...");
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
}
} |
package com.cv.java.multithreading;
/**
* @author Chandra Vardhan
*
*/
public class TestSynchronized {
public static void main(String args[]) {
Table obj = new Table();// only one object
// Table obj2 = new Table();
//Table obj = new Table();
/* TestThread1 t1 = new TestThread1(obj);
TestThread2 t2 = new TestThread2(obj);
TestThread3 t3 = new TestThread3(obj);
TestThread4 t4 = new TestThread4(obj);
TestThread1 t11 = new TestThread1(obj2);
TestThread2 t22 = new TestThread2(obj2);
TestThread3 t33 = new TestThread3(obj2);
TestThread4 t44= new TestThread4(obj);
t1.start();
t2.start();
t3.start();
t4.start();
// t11.start();
// t2.start();
// t33.start();
t44.start();*/
/*TestThread1 t1 = new TestThread1(obj);
TestThread5 t11 = new TestThread5(obj);
TestThread2 t2 = new TestThread2(obj);
TestThread3 t3 = new TestThread3(obj);
t1.start();
t11.start();
t3.start();
t2.start();*/
Table table = new Table(10);
//Table table2 = new Table(3);
EvenPrintThread t1 = new EvenPrintThread(table);
OddPrintThread t11 = new OddPrintThread(table);
t1.start();
t11.start();
Table table2 = new Table(5);
//Table table2 = new Table(3);
EvenPrintThread t111 = new EvenPrintThread(table2);
OddPrintThread t1111 = new OddPrintThread(table2);
t111.start();
t1111.start();
}
} |
package com.cv.java.multithreading;
/**
* @author Chandra Vardhan
*
*/
public class TestThread1 extends Thread {
Table t;
TestThread1(Table t) {
this.t = t;
}
public void run() {
Table.printSync1(10);
}
} |
package com.cv.java.multithreading;
public class TestThread2 extends Thread {
Table t;
TestThread2(Table t) {
this.t = t;
}
public void run() {
System.out.println("thread executing..."+TestThread2.class.getName());
Table.printStatic(100);
}
} |
package com.cv.java.multithreading;
public class TestThread3 extends Thread {
Table t;
TestThread3(Table t) {
this.t = t;
}
public void run() {
t.print(1000);
}
} |
package com.cv.java.multithreading;
public class TestThread4 extends Thread {
Table t;
TestThread4(Table t) {
this.t = t;
}
public void run() {
t.print(10000);
}
} |
package com.cv.java.multithreading;
/**
* @author Chandra Vardhan
*
*/
public class TestThread5 extends Thread {
Table t;
TestThread5(Table t) {
this.t = t;
}
public void run() {
Table.printSync2(11);
}
} |
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class Alphabet {
public static void main(String[] args) throws InterruptedException {
Numeric numeric = new Numeric();
numeric.start();
synchronized (Alphabet.class) {
for (int i = 65; i < 90; i++) {
System.out.print((char) i + " ");
}
Thread.sleep(1);
numeric.wait(0);
numeric.notify();
}
}
} |
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class Display {
public synchronized void wish(String name) {
for (int i = 0; i < 3; i++) {
System.out.println("good morning");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.err.println("Am interrupted...");
}
System.out.println(name);
}
}
public static synchronized void inform(String name) {
for (int i = 0; i < 3; i++) {
System.out.println("come for interview====");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Am interrupted...");
}
System.out.println(name);
}
}
public static void result(String name) {
for (int i = 0; i < 3; i++) {
System.out.println("you got selected====");
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
System.err.println("Am interrupted...");
}
System.out.println(name);
}
}
public void work(String name) {
for (int i = 0; i < 3; i++) {
System.out.println("you have to work====");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.err.println("Am interrupted...");
}
System.out.println(name);
}
}
} |
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class MyThread implements Runnable {
private Display display;
private String name;
public MyThread(Display display, String name) {
this.display = display;
this.name = name;
}
@Override
public void run() {
display.wish(name + "wish");
display.inform(name+"inform");
/*display.work(name+"work");
display.result(name+"result");*/
}
} |
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class Numeric extends Thread {
public void run() {
synchronized (this) {
for (int i = 65; i < 90; i++) {
System.out.print(i + " ");
this.notify();
try {
Thread.sleep(1);
if (i < 90) {
this.wait();
}
} catch (InterruptedException e) {
}
}
}
}
} |
/**
*
*/
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class SyncTest {
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
Display display2 = new Display();
MyThread myThread = new MyThread(display, "cv");
MyThread myThread2 = new MyThread(display2, "chote");
Thread thread = new Thread(myThread);// Even though wish method is
// synchronized we are get
// zig-zag results...
// inconsistent results...
// And we developed inform() method as static sync method...
Thread thread2 = new Thread(myThread2);
thread.start();
thread2.start();
//The below code will not give any problem...
/* Display display3 = new Display();
MyThread2 myThread3 = new MyThread2(display3, "cv");
MyThread2 myThread4 = new MyThread2(display3, "chote");
Thread thread3 = new Thread(myThread3);
Thread thread4 = new Thread(myThread4);
thread3.start();
thread4.start();*/
}
} |
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class ThreadA extends Thread {
int total = 0;
public void run() {
synchronized (this) {
System.out.println("child thread starts calculator");
for (int i = 1; i < 100; i++) {
total = total + i;
}
this.notifyAll();
System.out.println("waiting thread giving notification");
}
}
} |
package com.cv.java.synchronize;
/**
* @author Chandra Vardhan
*
*/
public class ThreadATest {
public static void main(String[] args) throws InterruptedException {
ThreadA threadb = new ThreadA();
ThreadA threadb2 = new ThreadA();
ThreadA threadb3 = new ThreadA();
threadb.start();
threadb2.start();
threadb3.start();
System.out.println("main thread call several wait() threads");
synchronized (threadb) {
threadb.wait();
System.out.println("main thread got notification");
/*threadb2.wait();
System.out.println("one more waiting thread");
threadb3.wait();
System.out.println("again");*/
}
System.out.println((threadb.total));
}
} |
No comments:
Post a Comment