Plan to write a "Java Concurrent basic Practice" series, counted as my Java concurrency Learning and practice of a simple summary. This is the first of the series that describes the easiest way to quit a concurrent task.
After a concurrent task is started, do not expect it to always perform. Due to time constraints, resource constraints, user actions, even exceptions in tasks (especially run-time exceptions), ... Can cause the task not to be completed. How to properly exit the task is a common problem, and the implementation method is also a lot of things.
1. Mission
Create a concurrent task that recursively gets the absolute path of all subdirectories and files under the specified directory, and then saves the path information to a file, as shown in Listing 1:
Listing 1 public class Filescanner implements Runnable {private File root = null;
Private list<string> filepaths = new arraylist<string> (); Public FileScanner1 (File root) {if (root = null | |!root.exists () | | |!root.isdirectory ()) {throw NE
W illegalargumentexception ("Root must be legal directory");
} this.root = root;
@Override public void Run () {travlefiles (root);
try {savefilepaths ();
catch (Exception e) {e.printstacktrace ();
} private void Travlefiles (File parent) {String FilePath = Parent.getabsolutepath ();
Filepaths.add (FilePath);
if (Parent.isdirectory ()) {file[] children = parent.listfiles ();
for (File Child:children) {travlefiles (child); }} private void Savefilepaths () throws IOException {FiLewriter fos = new FileWriter (New File (Root.getabsolutefile () + File.separator + "filepaths.out"));
for (String filepath:filepaths) {fos.write (FilePath + "\ n");
} fos.close (); }
}
2. Stop thread
There is a very straightforward, and simply, way to stop a thread, which is to invoke the Thread.stop () method, as shown in Listing 2:
Listing 2 public
static void Main (string[] args) throws Exception {
Filescanner task = new Filescanner (New File ("C:")); C3/>thread taskthread = new Thread (Task);
Taskthread.start ();
TimeUnit.SECONDS.sleep (1);
Taskthread.stop ();
}
However, the people of the Earth know that Thread.stop () was not recommended long ago. According to the official documentation, the method is inherently unsafe. When a thread is stopped, all of the monitoring locks that the thread occupies will be freed, which can cause inconsistencies in the objects protected by these locks. When you execute the application in Listing 2, the results of the operation are indeterminate. It may output a file that contains portions of the scanned directories and files. But it is also very likely that nothing will be output, because during the execution of the Filewriter.write (), the I/O exception may be caused by a thread stop, making it impossible to get the output file eventually.