"Java" Thread concurrent copy program

Source: Internet
Author: User
Tags file copy

It is said that Professor Li of the information College of a 211 university in Dalian is very good at this, he takes each operating system undergraduate class, each semester must complete this procedure, but the online information about this aspect is very few, only a C language version.

However, the previous students have been copied, the experimental results of Professor Li fooled the C language version, the class used, the thread and process is not very reasonable, a very simple program made very lengthy. Obviously this thread concurrent copy program only involves the thread mutually exclusive aspect, with the thread synchronization the slightest relation, this thread concurrently copies the program mutually exclusive, namely each thread operation's file can only be one, guarantees does not appear a file to be in the multi-file operation situation, does not have to do the other behavior after having done the copy, There is no need to communicate with other programs at all. The C language version, incredibly also to use the pipeline to achieve, so that you do not know the truth of the students, more confused is what to do. Pipeline in the previous "Java" Thread pipeline communication (click the Open link) I have said very detailed, here is not to repeat.

At the same time, Professor Li this question is not reasonable, even if there is no mutex, because it is a copy of the program, there will be no original folder files do not have the situation, even if the thread mutex is not implemented, the program can still run, but later copied over the text overwrite the previous copy of the file. If you give me a question, you should change the topic to "Thread concurrency cutter", so that students can really understand the importance of thread mutex.

However, there is a point still to praise Professor Li, this topic is absolutely his own original, online can not find any information, if pull to check the absolute clearance, unfortunately every semester Professor Li always let students solve their own problems, never publish reference answers let students learn, this is really very bad.

In order to let future students no longer suffer from their harm, to solve a variety of information can not be found, no one asked the pain. I have written this article, to you later with your own good Java to explain what is the thread concurrent copy program.


I. BASIC OBJECTIVES

We are going to make a program like this:

First, there are two folders in the F disk, a and b,f:\a a bunch of files inside, there is a folder "new Folder", and this folder is also a bunch of files.

The completed function is similar to "Java" using the file input and output stream to complete the operation of another folder that copies all the files in one folder (click to open the link),

After the program runs, all the files inside the f:\a will be copied to the f:\b, and all the files in the f:\b will be prefixed with the rename_, it is said that Professor Li very much like to let the students in the copy of the document to add their own school number, in order to maintain the originality of everyone, I can only say Oh, After you understand the whole program, I'll add "Professor Lee abc" to the front of each file ^_^


However, this thread concurrent copy program and "Java" using the file input and output stream to complete a folder to copy all the files in another folder operation (click the Open link) in the difference is, everyone please note the results of the eclipse inside, each file copy is done by different threads.

This is compared to the single thread of "Java" that uses the file input and output stream to complete another folder where all files in one folder are copied (click the Open link), and if you want to copy thousands of large files, this program is obviously more excellent.

In order to let everyone see the results of the experiment, deliberately let each thread after the copy stay for 1 seconds.


Second, the basic idea

It is said that Professor Li, in addition to the students to complete the process, but also must complete the flowchart to ensure that each student really want to understand ... As a result, a whole bunch of identical flowcharts appeared ...

In fact, the flowchart for each thread of this program is this:


As for the process of copying files, you can refer to my previous "Java" using the file input and output stream to complete a folder to copy all the files in another folder operation (click the Open link), thread concurrency, mutual exclusion and synchronization process, you can refer to my previous "Java" thread concurrency, Mutual exclusion and synchronization (click to open the link), even if you do not know what is the Java input and output stream, you can refer to my previous "Java" print stream and buffer readers to complete the input and output to the file operation (click to open the link), the article also used the critical section and critical resources concept, Also do not understand can refer to my previous "Java" using synchronized (this) to complete the critical section of the thread (click to open the link), novice to, NCLB, indefatigable, guaranteed as long as will write Java absolutely understand.


Third, the production process

1, first and "Java" thread concurrency, mutual exclusion and synchronization (click to open the link) the same as in the main function threadfilecopy define a process filecopy, and then in the inside open four processes:

public class Threadfilecopy {public static void main (string[] args) throws Exception {FileCopy FileCopy = new FileCopy ("F: /a "," f:/b "), new Thread (FileCopy," Thread 1 "). Start (); New Thread (FileCopy," Thread 2 "). Start (); New Thread (FileCopy," Thread 3 "). Start (); New Thread (FileCopy, "Thread 4"). Start ();}}

The Process class FileCopy has a constructor with parameters, which requires you to pass the original path of the copy and copy the new path in, here with the "Java" using the file input and output stream to complete a folder to copy all the files in another folder operation (click the Open link).


2, then is the core of the entire program, using the Runnable process class FileCopy

In fact, the entire program is "Java" using synchronized (this) to complete the critical section of the thread (click the Open link) and the "Java" using the file input and output stream to complete a folder to copy all the files in another folder operation "(click Open link) two program merge , "Java" uses synchronized (this) to complete the critical section of the thread (click Open link) is for thread concurrency, "Java" Using the file input and output stream to complete the copy of all files within a folder of the other folder Operation "(click the Open link) is for the copy, So there is the following love crystallization:

Class FileCopy implements Runnable {//First is constructor, member declaration part private String Oldpath;private string newpath;//This i is a cursor, A cursor that is recorded to the first number of copies of the file, and the cursor is moved down//at the same time this I is also the so-called "critical resource" private int i = 0;public FileCopy (string OldPath, String NewPath) { This.oldpath = Oldpath;this.newpath = NewPath;} public void Run () {try {(new File (NewPath)). Mkdirs (); File FileList = new file (OldPath); string[] File = Filelist.list (); File TEMP = Null;//file.length The total number of files taken while (I < file.length) {synchronized (this) {///copy file is a critical section, allowing only one thread to enter operation if ( Oldpath.endswith (file.separator)) {temp = new file (OldPath + file[i]);} else {temp = new file (OldPath + file.separator + F Ile[i]);} System.out.println (Thread.CurrentThread (). GetName () + "copying" + temp), if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp);//Copy to a new location and prefix rename_ in this sentence, save you guys in the end of the final design of the bitter force! FileOutputStream output = new FileOutputStream (newpath+ "/" + "rename_" + (Temp.getname ()). ToString ()); byte[] Bufferarray = new byte[1024 * 64];int prereadlength;while (prereadlength = InpuT.read (bufferarray))! =-1) {output.write (Bufferarray, 0, prereadlength);} Output.flush (); Output.close (); Input.close ();} if (Temp.isdirectory ()) {FileCopy (OldPath + "/" + file[i], NewPath + "/" + File[i]);} i++;} After each thread has finished, sleep for 1 seconds, rest, after all, I want to see the results of the experiment Thread.CurrentThread (). Sleep (1000);}} catch (Exception e) {//Stop process Thread.yield () if the program has finished reading);}} The exact same method as above, purely for implementation if you encounter a cursor folder, use iterations to complete the copy operation of the file within the folder private void FileCopy (String oldpath, String NewPath) {try {(new File (NewPath)). Mkdirs (); File FileList = new file (OldPath); string[] File = Filelist.list (); File temp = null;for (int i = 0; i < file.length; i++) {if (Oldpath.endswith (file.separator)) {temp = new file (OldPath + File[i]);} else {temp = new File (OldPath + file.separator + file[i]);} System.out.println (Thread.CurrentThread (). GetName () + "copying" + temp), if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp); FileOutputStream output = new FileOutputStream (newpath+ "/" + "rename_" + (Temp.getname ()). ToString ()); byte[] Bufferarray = new Byte[1024 * 64];int prereadlength;while ((prereadlength = Input.read (bufferarray))! =-1) {output.write (Bufferarray, 0, Preread length);} Output.flush (); Output.close (); Input.close ();} if (Temp.isdirectory ()) {FileCopy (OldPath + "/" + file[i], NewPath + "/" + File[i]);}}} catch (Exception e) {Thread.yield ();}}}

3, therefore the entire procedure is as follows:

Import Java.io.*;class FileCopy implements Runnable {//First is constructor, member declaration part private String Oldpath;private string newpath;// This i is a cursor, which is recorded to the copy of the first few files of the cursor, the copy is completed this cursor is down//at the same time this I is also so-called "critical resource" private int i = 0;public FileCopy (string OldPath, String NewPath) {This.oldpath = Oldpath;this.newpath = NewPath;} public void Run () {try {(new File (NewPath)). Mkdirs (); File FileList = new file (OldPath); string[] File = Filelist.list (); File TEMP = Null;//file.length The total number of files taken while (I < file.length) {synchronized (this) {///copy file is a critical section, allowing only one thread to enter operation if ( Oldpath.endswith (file.separator)) {temp = new file (OldPath + file[i]);} else {temp = new file (OldPath + file.separator + F Ile[i]);} System.out.println (Thread.CurrentThread (). GetName () + "copying" + temp), if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp);//Copy to a new location and prefix rename_ in this sentence, save you guys in the end of the final design of the bitter force! FileOutputStream output = new FileOutputStream (newpath+ "/" + "rename_" + (Temp.getname ()). ToString ()); byte[] Bufferarray = new byte[1024 * 64];int Prereadlength;while (preReadlength = Input.read (bufferarray))! =-1) {output.write (Bufferarray, 0, prereadlength);} Output.flush (); Output.close (); Input.close ();} if (Temp.isdirectory ()) {FileCopy (OldPath + "/" + file[i], NewPath + "/" + File[i]);} i++;} After each thread has finished, sleep for 1 seconds, rest, after all, I want to see the results of the experiment Thread.CurrentThread (). Sleep (1000);}} catch (Exception e) {//Stop process Thread.yield () if the program has finished reading);}} The exact same method as above, purely for implementation if you encounter a cursor folder, use iterations to complete the copy operation of the file within the folder private void FileCopy (String oldpath, String NewPath) {try {(new File (NewPath)). Mkdirs (); File FileList = new file (OldPath); string[] File = Filelist.list (); File temp = null;for (int i = 0; i < file.length; i++) {if (Oldpath.endswith (file.separator)) {temp = new file (OldPath + File[i]);} else {temp = new File (OldPath + file.separator + file[i]);} System.out.println (Thread.CurrentThread (). GetName () + "copying" + temp), if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp); FileOutputStream output = new FileOutputStream (newpath+ "/" + "rename_" + (Temp.getname ()). ToString ()); byte[] BufferaRray = new byte[1024 * 64];int prereadlength;while ((prereadlength = Input.read (bufferarray))! =-1) {Output.write (Buffera Rray, 0, prereadlength);} Output.flush (); Output.close (); Input.close ();} if (Temp.isdirectory ()) {FileCopy (OldPath + "/" + file[i], NewPath + "/" + File[i]);}}} catch (Exception e) {Thread.yield ();}}} public class Threadfilecopy {public static void main (string[] args) throws Exception {FileCopy FileCopy = new FileCopy ("F: /a "," f:/b "), new Thread (FileCopy," Thread 1 "). Start (); New Thread (FileCopy," Thread 2 "). Start (); New Thread (FileCopy," Thread 3 "). Start (); New Thread (FileCopy, "Thread 4"). Start ();}}

iv. Outlook

This program is still a bit of a flaw, because once the file cursor encounters a folder, using an iterative method to complete the copy, while the operation of the thread still exists in the critical section, so if the file cursor encountered in the folder "new Folder" inside the F:\a file, can only use a single thread to complete the "new folder" The files inside the copy work, can not be concurrent, after all, iterative this way in the actual programming, you'd better not to play like this, will form a high time complexity and space complexity, this is the second, mainly other people are more difficult to read. How to complete the concurrency of threads in an iteration is a question worth thinking about, but the copy of the file in the root directory is definitely thread-parallel.

"Java" Thread concurrent copy program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.