0% found this document useful (0 votes)
3 views1 page

Java Thread Example with Join Method

The document contains a Java program that creates and runs 10 threads, each printing a greeting and farewell message. The main thread starts the child threads and waits for their completion using the join() method. Finally, it prints a message indicating the end of the main thread's execution.

Uploaded by

hoangtu112201
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Java Thread Example with Join Method

The document contains a Java program that creates and runs 10 threads, each printing a greeting and farewell message. The main thread starts the child threads and waits for their completion using the join() method. Finally, it prints a message indicating the end of the main thread's execution.

Uploaded by

hoangtu112201
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# ex1.

java

class C extends Thread {


int i;
C(int i) { this.i = i; }
public void run() {
[Link]("Thread " + i + " says hi");
try {
sleep(500);
} catch (InterruptedException e) {}
[Link]("Thread " + i + " says bye");
}
}

public class ex1 {


private static final int NUM_THREAD = 10;
public static void main(String[] args) {
[Link]("main thread start!");
C[] c = new C[NUM_THREAD];
for(int i=0; i < NUM_THREAD; ++i) {
c[i] = new C(i);
c[i].start();
}
[Link]("main thread calls join()!");
for(int i=0; i < NUM_THREAD; ++i) {
try {
c[i].join();
} catch (InterruptedException e) {}
}
[Link]("main thread ends!");
}
}
Beta
0 / 0
used queries
1

Common questions

Powered by AI

The main thread in the Java program uses the 'join()' method to ensure it completes after all created threads finish. By invoking 'join()' on each thread 'C[i]' within a loop, the main thread waits for each thread's execution to end before proceeding to print 'main thread ends!'. This creates a blocking mechanism that halts the main thread’s progress until all threads have finished, ensuring synchronized execution of the program .

The exception handling strategy for 'InterruptedException' in the 'ex1' Java program is minimal and lacks redundancy. The program uses an empty catch block for 'InterruptedException', which can obscure any problems in interrupt handling while wasting resources. A better strategy might include logging the exception or taking corrective measures. This oversight can impact debugging and runtime diagnoses, especially when threads are expected to be interrupted under certain conditions .

Upon execution of the 'ex1' Java program, the main thread begins by printing 'main thread start!'. It then initializes and starts 10 threads of class 'C'. Each 'C' thread when started, prints 'Thread i says hi', sleeps for 500 milliseconds, then prints 'Thread i says bye'. Meanwhile, the main thread calls 'join()' on each 'C' thread in sequential order, ensuring it pauses execution to wait for their completion. Only after all threads have finished does the main thread print 'main thread ends!', illustrating a synchronized and orderly thread execution pattern .

Using 'sleep()' in a thread can lead to issues such as increased run time and unpredictable scheduling. The 'sleep()' method pauses the current thread, potentially allowing other threads to execute. This does not guarantee they will start running immediately after sleep, as thread scheduling is controlled by the JVM and underlying operating system. Moreover, if 'sleep()' is used without handling 'InterruptedException' properly, the program might behave unpredictably if interruptions occur .

To improve scalability in the 'ex1' program, replace the hardcoded 'NUM_THREAD' and implement logic that allows dynamic configuration, either through command-line arguments or configuration files. This enables flexibility in deploying different numbers of threads based on the workload or environment. Moreover, consider using a thread pool provided by Java's 'ExecutorService' to efficiently manage a large number of threads, optimize system resources, and reduce overhead from creating and destroying threads .

Using 'System.out.println()' for logging within a thread's 'run' method is simple but not optimal for multithreading environments, as it doesn't provide control over log formatting, levels, or outputs congested logs due to unsynchronized access to the console. For better logging, consider using a logging framework such as 'java.util.logging' or 'Log4j' that supports concurrent writing, log levels, and flexible output options, improving log management and readability in multithreaded applications .

The execution order of threads in the 'ex1' Java program is determined by the JVM and underlying OS scheduler, leading to non-deterministic output. Each thread prints messages independently upon starting and concluding. A different scheduling order could result in variations in which 'Thread i says hi' and 'Thread i says bye' appear interleaved, but the final print message, 'main thread ends!', remains constant due to the use of 'join()', which ensures all threads complete before termination. Thus, while messages between threads vary, program synchronization remains intact .

In the 'ex1' program, thread synchronization is demonstrated by using the 'join()' method on each thread created. The 'join()' method is called in a loop following the start of all threads. This ensures that the 'main' thread waits for each of the ten 'C' threads to complete their execution before continuing with its flow. As a result, 'main thread ends!' will only be printed after all threads have finished execution, ensuring synchronized termination of threads .

Extending the 'Thread' class is less flexible compared to implementing the 'Runnable' interface because Java does not support multiple inheritance. By extending 'Thread', a class cannot inherit from any other classes. Implementing 'Runnable' allows a class to extend from another class if required, promoting better object-oriented design choices by separating the task (runnable) from thread management (Thread class).

Using hardcoded constants like 'NUM_THREAD' in the 'ex1' Java program makes adjusting the number of threads inflexible. The constant needs to be changed directly in the code which can lead to higher maintenance costs and potential for errors. For scalability and adaptability, it is generally preferred to configure such values dynamically or through external configuration files to allow better management and adaptability of the program to different environments .

You might also like