import java.io.FileWriter;
import java.io.IOException;
These lines import necessary classes from the java.io package. FileWriter is used to write characters to a file, and IOException is an exception that might be thrown during input-output operations.
class NumberWriter extends Thread {
Defines a new class named NumberWriter which extends the Thread class. This suggests that instances of NumberWriter can be executed concurrently.
private final int startNumber;
private final int endNumber;
private final String fileName;
Declares three private instance variables: startNumber, endNumber, and fileName. These variables will hold the starting and ending numbers for the range of numbers to be written, and the filename to which these numbers will be written.
public void run() {
This method overrides the run() method defined in the Thread class. It is the entry point for the concurrent execution of this thread.
try {
FileWriter writer = new FileWriter(fileName);
Creates a new FileWriter object with the specified fileName. This object will be used to write data to the file.
public class Main {
public static void main(String[] args) {
NumberWriter oddWriter = new NumberWriter(1, 150, "odd_numbers.txt");
NumberWriter evenWriter = new NumberWriter(2, 150, "even_numbers.txt");
In the Main class, two instances of NumberWriter are created: oddWriter to write odd numbers and evenWriter to write even numbers. Each instance is initialized with appropriate start and end numbers along with the filename.
oddWriter.start();
evenWriter.start();
Starts the execution of both oddWriter and evenWriter threads concurrently.
try {
oddWriter.join();
evenWriter.join();
The main thread (represented by main()) waits for both oddWriter and evenWriter threads to finish executing using the join() method. This ensures that the message "Numbers written successfully." is printed only after both threads have completed their execution.
System.out.println("Numbers written successfully.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Prints a message indicating that numbers have been successfully written to the files once both threads have completed. Also, catches and prints any InterruptedException that might occur during the waiting process.
Auf dieser Seite können Sie das Online-Video File Handling Using Thread in Java mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Anindita Das Bhattacharjee 08 Mai 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 696 Mal angesehen und es wurde von 78 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!