Experiment 1: design ideas
Create two threads. After thread 1 redirects the standard output stream, thread 2 starts to print output and view the output location. To determine if thread 2 is affected. The code is as follows:
public static void main( String[] args ){ new Thread(new Runnable() { @Override public void run() { System.out.println("Thread 1 starts redirecting output stream"); try { // Thread 1 redirects the standard output stream to a file, and the printout will be output to the file later System.setOut(new PrintStream(new FileOutputStream(new File("E:\\ouputfile.txt")))); System.out.println("Finished redirecting output stream for thread 1"); } catch (FileNotFoundException e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { try { // Thread 2 sleeps for 3s and waits for redirection to complete before printing output Thread.sleep(3000); System.out.println("Thread 2 output position determination??"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); }
Experiment 1: output results
The output of the console is: only print the text before thread 1 starts redirection
Reset output to back file:
You can see that the printout of thread 2 is also affected.
Experiment 1: conclusion
1. No matter which thread redirects the output stream, all threads will be affected. 2. Guess that the redirection input stream is the same. Experiment 2: influence range of redirection operationExperiment 2: design ideas
Start two JVM processes. The JVM process 1 redirects and process 2 prints normally. Check the print location of process 2 to determine whether process 2 is affected.
The process 1 code is as followspublic static void main( String[] args ){ System.out.println("Process 1 starts redirecting output stream"); try { System.setOut(new PrintStream(new FileOutputStream(new File("E:\\ouputfile.txt")))); System.out.println("Finished redirecting output stream for process 1"); } catch (FileNotFoundException e) { e.printStackTrace(); } String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name.split("@")[0]; System.out.println("Process number" + pid); // Dead cycle while (true) { } }The code of process 2 is as follows. This process will run after process 1 redirection
public static void main(String[] args) { String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name.split("@")[0]; System.out.println("Process number:" + pid + "See where this text goes"); while (true) { } }
Experiment 2: output results
Process 1 console output
Process 2 console output
Process 1 reset backward output file
Obtain two process numbers, process number 1:3428 and process number 2:6072. Find the corresponding process.