After reading Java advanced programming in the past two days, I can see the following example. I think it is suitable for beginners to learn thread, so I will record it for them to learn from cainiao like me, you can ignore it directly.
Idea: Improve and improve the functions of this program, and create your own download tool. )
This program has three main classes: downloader, downloadmanager, and downloadfiles.
1. downloader: reads and writes data.
2. downloadmanager: Mainly used to control downloads. It has functions such as start, pause, resume, and stop.
3. downloadfiles: enter a URL in the text box and create an instance of the corresponding downloadmanager class.
Knowledge points involved include thread, synchronized, I/O stream, and layout manager (mainly gridbaglayout and Its Constraints gridbagconstraints)
Downloader class
Import Java. AWT. gridbagconstraints; import Java. AWT. gridbaglayout; import Java. AWT. insets; import Java. io. bufferedinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import java.net. URL; import java.net. urlconnection; import javax. swing. jlabel; import javax. swing. joptionpane; import javax. swing. J Panel; import javax. swing. jprogressbar; import javax. swing. swingutilities;/*** read and write data **/public class downloader extends jpanel implements runnable {Private Static final long serialversionuid = 216695025314371191l; Private Static final int buffer_size = 1000; // byte array size protected URL DownLoadURL; // The downloaded resource's urlprotected inputstream; // The super class protected outputstream of all byte input streams; // all of the byte output streams Class superclass protected byte [] buffer; // protected int filesize in the buffer array; // file size protected int bytesread; // number of bytes read protected jlabel urllabel; // place the URL's jlabelprotected jlabel sizelabel; // place the jlabelprotected jlabel completelabel; // place the downloaded jlabelprotected jprogressbar progressbar; // progress bar protected Boolean stopped = false; // indicates whether to stop downloading. Protected Boolean sleepscheduled = false; // indicates whether to pause for a period of time. Protected Boolean suincluded = false; // whether the thread suspends public final static int sleep_time = 5*1000; // pause protected thread thisthread for 5 seconds; // current thread public static threadgroup downloadergroup = new threadgroup ("donwload Threads"); // thread group public downloader (URL, fileoutputstream FOS) throws ioexception {DownLoadURL = URL; outputstream = Fos; bytesread = 0; // urlconnection constructs a URL Connection to the specified URL. Urlconnection = DownLoadURL. openconnection (); filesize = urlconnection. getcontentlength (); // file length if (filesize =-1) {Throw new filenotfoundexception (URL. tostring ();} // an internal buffer array is created when bufferedinputstream is created. Inputstream = new bufferedinputstream (urlconnection. getinputstream (); buffer = new byte [buffer_size]; thisthread = new thread (downloadergroup, this); buildlayout ();} private void buildlayout () {jlabel label Label; setlayout (New gridbaglayout (); gridbagconstraints GBC = new gridbagconstraints (); // This field is used when the display area of the component is greater than the size of the display area requested by the component. Horizontal: Adjust the component size in the horizontal direction rather than the vertical direction. GBC. fill = gridbagconstraints. horizontal; // The minimum gap between the insets component and the edge of the display area GBC. insets = new insets (5, 10, 5, 10); // specify the "cell" that contains the start edge of the display area of the component, where the first cell of the row is gridx = 0. GBC. gridx = 0; label = new jlabel ("Address:", jlabel. left); add (Label, GBC); label = new jlabel ("Progress:", jlabel. left); add (Label, GBC); label = new jlabel ("downloaded:", jlabel. left); add (Label, GBC); GBC. gridx = 1; // gridwidth: specify the number of cells in a row of the component display area. Remainder: specify that this component is the last component in its row or column GBC. gridwidth = gridbagconstraints. remainder; // weightx: specify how to distribute extra horizontal space. // If the layout is smaller than the area to be filled in the horizontal direction, the system distributes the extra space to each column according to the weight ratio. // Columns with zero weight will not get extra space. GBC. weightx = 1; urllabel = new jlabel (DownLoadURL. tostring (); add (urllabel, GBC); progressbar = new jprogressbar (0, filesize ); // set the value of the stringpainted attribute // This attribute determines whether the progress bar should present a progress string. Progressbar. setstringpainted (true); add (progressbar, GBC); GBC. gridwidth = 1; completelabel = new jlabel (integer. tostring (bytesread); add (completelabel, GBC); GBC. gridx = 2; GBC. weightx = 0; // This field is used when the widget is smaller than the display area. // It determines the position of the component in the display area. GBC. anchor = gridbagconstraints. east; label = new jlabel ("file size:", jlabel. left); add (Label, GBC); // specify the "cell" that contains the start edge of the display area of the component. The first cell of the row is gridx = 0. GBC. gridx = 3; GBC. weightx = 1; sizelabel = new jlabel (integer. tostring (filesize); add (sizelabel, GBC);} public void run () {javasmdownload () ;}/ *** is responsible for executing the download method. */Private void merge mdownload () {int bytecount; // refresh progress bar and completelabel: the runnable progressbarupdate = new runnable () {public void run () is synchronized between the AWT time thread and the download thread () {progressbar. setvalue (bytesread); completelabel. settext (integer. tostring (bytesread) ;}}; while (bytesread <filesize )&&(! Isstopped () {// whether to suspend if (issleepscheduled () {try {thread. sleep (sleep_time);} catch (interruptedexception e) {setstopped (true); break;} setsleepscheduled (false);} Try {// read a certain number of bytes from the input stream, and store it in the buffer Array Buffer // return the actual number of bytes read in integer form. Stored in the buffer integer bytecount. Bytecount = inputstream. read (buffer); If (bytecount =-1) {setstopped (true); break;} else {outputstream. write (buffer, 0, bytecount); bytesread + = bytecount; // progress bar thread (invokelater () of the swingutilities class that can be called to create a multithreaded application if you need to modify the visualization component () method and invokeandwait () method) swingutilities. invokelater (progressbarupdate);} catch (ioexception e) {setstopped (true); joptionpane. showmessagedialog (this, E. getmessage (), "I/O error", joptionpane. err Or_message); break;} // whether to pause synchronized (this) {If (issuincluded () {try {// The download thread calls wait () after the method is used, the ownership of the monitoring is implicitly waived. This. wait () ;}catch (interruptedexception e) {setstopped (true); break ;}setsuincluded (false) ;}// test whether the current thread has been interrupted. If (thread. interrupted () {setstopped (true); break ;}try {// close the stream and disconnect from the downloaded file inputstream. close (); outputstream. close ();} catch (ioexception e) {e. printstacktrace ();} // is the download complete? If (bytesread = filesize) {joptionpane. showmessagedialog (null, "download completed", "download completed! ", Joptionpane. information_message); // system. exit (1) ;}} public synchronized void startdownload () {thisthread. start ();} public synchronized void stopdownload () {thisthread. interrupt ();} The Public synchronized void resumedownloader () {// y () and policyall () methods do not let the waiting thread wait for immediate response. // Wait for the thread to reply to the execution, you must first obtain the object monitoring synchronized with the thread this. notify ();} public synchronized void setstopped (Boolean stopped) {This. stopped = stopped;} public synchronized Boolean isstopped () {return stopped;} public synchronized void setsleepscheduled (Boolean sleepscheduled) {This. sleepscheduled = sleepscheduled;} public synchronized Boolean issleepscheduled () {return sleepscheduled;} public synchronized void setsuspended (Boolean Suincluded) {This. suincluded = suincluded;} public synchronized Boolean issuincluded () {return suincluded;} public static void cancelallandwait () {// activecount () returns the number of active threads in the thread group. Int COUNT = downloadergroup. activecount (); thread [] threads = new thread [count]; // enumerate () Stores reference of each active thread in the threads array. Count = downloadergroup. enumerate (threads); downloadergroup. interrupt (); For (INT I = 0; I <count; I ++) {try {threads [I]. join ();} catch (interruptedexception e) {e. printstacktrace () ;}}/ ** Note: The suincluded (), resume (), and stop () methods in the Thread class are outdated. * This is not called either. Instead, you can manually implement the corresponding functions. */}}
Downloadmanager classImport Java. AWT. borderlayout; import Java. AWT. gridlayout; import Java. AWT. event. actionevent; import Java. AWT. event. actionlistener; import Java. io. fileoutputstream; import Java. io. ioexception; import java.net. URL; import javax. swing. jbutton; import javax. swing. jpanel; import javax. swing. border. bevelborder; import javax. swing. border. border; import javax. swing. border. titledborder;/*** control download: Start, pause, stop */Public CIA SS downloadmanager extends jpanel {Private Static final long serialversionuid = response; protected downloader; protected jbutton startbutton; // start protected jbutton sleepbutton; // pause protected jbutton suspendbutton for 5 seconds; // pause protected jbutton resumebutton; // restore protected jbutton stopbutton; // stop public downloadmanager (URL, fileoutputstream FOS) throws ioexception {downloader = new dow Nloader (URL, FOS); buildlayout (); Border border = new bevelborder (bevelborder. raised); string name = URL. tostring (); int Index = Name. lastindexof ('/'); border = new titledborder (border, name. substring (index + 1); setborder (Border);} private void buildlayout () {setlayout (New borderlayout (); // bevelborder: This class implements a simple double-line inclined border. Downloader. setborder (New bevelborder (bevelborder. raised); add (downloader, borderlayout. center); add (getbuttonpanel (), borderlayout. south);} // place the jpanelprivate jpanel getbuttonpanel () {jpanel outerpanel; // adjust the layout. Jpanel innerpanel = new jpanel (); innerpanel. setlayout (New gridlayout (1, 5, 10, 0); startbutton = new jbutton ("START"); startbutton. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {startbutton. setenabled (false); sleepbutton. setenabled (true); resumebutton. setenabled (false); suspendbutton. setenabled (true); stopbutton. setenabled (true); Downloader. startdownload () ;}}); innerpanel. add (startbutton); sleepbutton = new jbutton ("tentative 5 seconds"); sleepbutton. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {Downloader. setsleepscheduled (true) ;}}); innerpanel. add (sleepbutton); suspendbutton = new jbutton ("Suspend"); suspendbutton. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {suspendbutton. setenabled (false); resumebutton. setenabled (true); stopbutton. setenabled (true); Downloader. setsuincluded (true) ;}}); innerpanel. add (suspendbutton); resumebutton = new jbutton ("resume download"); resumebutton. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {resumebutton. setenabled (false); suspendbutton. setenabled (true); stopbutton. setenabled (true); Downloader. resumedownloader () ;}}); innerpanel. add (resumebutton); stopbutton = new jbutton ("stop"); stopbutton. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {stopbutton. setenabled (false); sleepbutton. setenabled (false); suspendbutton. setenabled (false); resumebutton. setenabled (false); startbutton. setenabled (true); Downloader. stopdownload () ;}}); innerpanel. add (stopbutton); outerpanel = new jpanel (); outerpanel. add (innerpanel); Return outerpanel ;}}Downloadfiles class
Import Java. AWT. borderlayout; import Java. AWT. gridbagconstraints; import Java. AWT. gridbaglayout; import Java. AWT. event. actionevent; import Java. AWT. event. actionlistener; import Java. io. file; import Java. io. fileoutputstream; import java.net. URL; import java.net. urlconnection; import javax. swing. jbutton; import javax. swing. jframe; import javax. swing. jlabel; import javax. swing. joptionpane; import javax. swing. jpane L; import javax. swing. jscrollpane; import javax. swing. jtextfield; import javax. swing. uimanager;/*** enter the URL in the text box and create an instance of the corresponding downloadmanager class */public class downloadfiles extends jpanel {Private Static final long serialversionuid = 2575460962137056640l; protected jpanel listpanel; // place the protected gridbagconstraints constraints on each downloaded Panel; // specify the constraints of components configured using the gridbaglayout class. Protected final string filepath = "D:/"; // path for saving the downloaded file private int taskcount = 0; static jframe frame; public static void main (string [] ARGs) {frame = new jframe ("from cannel_2020's blog (csdn)"); downloadfiles df = new downloadfiles (); frame. setdefaclocloseoperation (jframe. exit_on_close); frame. getcontentpane (). add (DF); frame. setsize (700,400); frame. setvisible (true);} public downloadfiles () {try {// set the appearance // uima Nager. setlookandfeel (uimanager. getsystemlookandfeelclassname (); uimanager. setlookandfeel ("com. sun. java. swing. plaf. nimbus. nimbuslookandfeel "); // uimanager. setlookandfeel ("com. sun. java. swing. plaf. motif. motiflookandfeel "); // uimanager. setlookandfeel (uimanager. getcrossplatformlookandfeelclassname (); // uimanager. setlookandfeel ("javax. swing. plaf. metal. metallookandfeel ");} catch (exception e) {e. print Stacktrace ();} setlayout (New borderlayout (); listpanel = new jpanel (); listpanel. setlayout (New gridbaglayout (); constraints = new gridbagconstraints (); constraints. gridx = 0; constraints. weightx = 1; constraints. fill = gridbagconstraints. horizontal; constraints. anchor = gridbagconstraints. north; jscrollpane JSP = new jscrollpane (listpanel); add (JSP, borderlayout. center); add (getaddurlpanel (), borderlayout. South);} // address bar, two buttons: Private jpanel getaddurlpanel () {jpanel Panel = new jpanel (); jlabel label = new jlabel ("url "); final jtextfield textfield = new jtextfield (30); Final jbutton downloadbutton = new jbutton ("click to download"); actionlistener = new actionlistener () {public void actionreceivmed (actionevent E) {New thread () {public void run () {downloadbutton. settext ("connecting"); downloadbutton. setenabled (Fals E); If (createdownloader (textfield. gettext () {textfield. settext (""); ++ taskcount; frame. settitle ("Total:" + taskcount + "download tasks"); revalidate ();} downloadbutton. settext ("click to download"); downloadbutton. setenabled (true );}}. start () ;}}; textfield. addactionlistener (actionlistener); // added the actionlistener listener and press enter to download the downloadbutton. addactionlistener (actionlistener); jbutton clearall = new jbutton ("Clear all"); clearall. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {Downloader. cancelallandwait (); listpanel. removeall (); revalidate (); repaint () ;}}); panel. add (Label); panel. add (textfield); panel. add (downloadbutton); panel. add (clearall); Return Panel;} private Boolean createdownloader (string URL) {try {URL DownLoadURL = new URL (URL); urlconnection = DownLoadURL. openconnection (); int length = urlc Onnection. getcontentlength (); If (length <0) {Throw new exception ("the length of the downloaded object cannot be determined! ");} Int Index = URL. lastindexof ('/'); file = new file (filepath + URL. substring (index + 1); If (file. exists () {joptionpane. showmessagedialog (this, "this file already exists", "cannot be downloaded", joptionpane. error_message); Return false;} fileoutputstream Fos = new fileoutputstream (File); // filepath + URL. substring (index + 1) // bufferedoutputstream Bos = new bufferedoutputstream (FOS); downloadmanager dm = new downloadmanager (DownLoadURL, FOS); listpanel. Add (DM, constraints); Return true;} catch (exception e) {joptionpane. showmessagedialog (this, "This resource cannot be downloaded. "," Cannot be downloaded! ", Joptionpane. error_message) ;}return false ;}}Running result: