Exercise 1
Exercise 1
public class TwoThread extends Thread { public void run() { for ( int i = 0; i < 20; i++ ) {
System.out.println(Thread.currentThread ().getName()); } } public static void main(String[] args) {
TwoThread T1 = new TwoThread(); T1.start(); for ( int i = 0; i < 20; i++ ) {
System.out.println("Main thread"); } } }
Answer:
3-Modify the previous program so that: create 2 others threads T2 and T3 using the class Thread
and TwoThread. Execute the program and explain what you see ?
Answer:
public class TwoThread extends Thread {
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName());
}
}
T1.start();
T2.start();
T3.start();
In this modified program, we create two additional threads (T2 and T3) using the Thread
class and passing an instance of the TwoThread class as the Runnable parameter. Then, we
start all three threads (T1, T2, and T3). When you execute this modified program, you will
see the output with interleaved thread names and "Main thread" messages from all three
threads. The exact interleaving of the output may vary on each run due to the concurrent
nature of the threads.
4-Modify the previous program so that the thread T2 complete its execution by blocking all
others thread after that they can run. Note: you can use join() method. The join() method is
used to hold the execution of currently running thread until the specified thread is
dead(finished execution).
Answer:
public class TwoThread extends Thread {
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName());
}
}
T1.start();
try {
T2.start();
T2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
T3.start();
Exercise 2: Write in java a program that uses two threads in parallel: - the first will display
the 26 letters of the alphabet; - the second will display numbers from 1 to 26. - the second
thread must wait 200 ms after it end.
Answer:
public class AlphabetThread extends Thread {
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
}
}
alphabetThread.start();
try {
alphabetThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
numberThread.start();
}
}