Sei sulla pagina 1di 3

Ex No.

19
Date:
Multi threading
Aim:
To write a java program to illustrate multithreading.
Source Code:
public class ThreadCountdownExtThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
private int threadNumber = ++threadCount;
public ThreadCountdownExtThread() {
System.out.println("\nStarting thread number => " + threadCount + "\n");
}
public void run() {
while(true) {
System.out.println(" - Thread number " + threadNumber +
" ( Current Countdown = " + countDown + " )");
for (int j = 0; j < 300000000; j++) {
// This is a test...
}
if (--countDown == 0) {
System.out.println(
"\nEnding thread number => " + threadNumber + "\n");
return;
}
}
}
private static void doThreadCountdown()
throws java.lang.InterruptedException {
for (int i = 0; i < 5; i++) {
Thread.sleep(2000);
new ThreadCountdownExtThread().start();
}
System.out.println("\n<< All threads have now been started!!! >>\n");
}
public static void main(String[] args)
throws java.lang.InterruptedException {
System.out.println("\n<< MAIN METHOD (Begin) >>");
doThreadCountdown();
System.out.println("<< MAIN METHOD (End) >>\n");
}
}
Output:
Javac ThreadCountdownExtThread.java
Java ThreadCountdownExtThread
<< MAIN METHOD (Begin) >>
Starting thread number => 1
- Thread number 1 ( Current Countdown = 5 )
- Thread number 1 ( Current Countdown = 4 )
- Thread number 1 ( Current Countdown = 3 )
- Thread number 1 ( Current Countdown = 2 )
- Thread number 1 ( Current Countdown = 1 )
Ending thread number => 1
Starting thread number => 2
- Thread number 2 ( Current Countdown = 5 )
- Thread number 2 ( Current Countdown = 4 )
- Thread number 2 ( Current Countdown = 3 )
- Thread number 2 ( Current Countdown = 2 )
- Thread number 2 ( Current Countdown = 1 )
Ending thread number => 2
Starting thread number => 3
- Thread number 3 ( Current Countdown = 5 )
- Thread number 3 ( Current Countdown = 4 )
- Thread number 3 ( Current Countdown = 3 )
- Thread number 3 ( Current Countdown = 2 )
- Thread number 3 ( Current Countdown = 1 )
Ending thread number => 3
Starting thread number => 4
- Thread number 4 ( Current Countdown = 5 )
- Thread number 4 ( Current Countdown = 4 )
- Thread number 4 ( Current Countdown = 3 )
- Thread number 4 ( Current Countdown = 2 )
- Thread number 4 ( Current Countdown = 1 )
Ending thread number => 4
Starting thread number => 5
<< All threads have now been started!!! >>
- Thread number 5 ( Current Countdown = 5 )
<< MAIN METHOD (End) >>
- Thread number 5 ( Current Countdown = 4 )
- Thread number 5 ( Current Countdown = 3 )
- Thread number 5 ( Current Countdown = 2 )
- Thread number 5 ( Current Countdown = 1 )
Ending thread number => 5
Result:
Thus a java program has been written for multithreading.

Potrebbero piacerti anche