Package main;
/**
* Created by lxj-pc on 2017/6/27.
*/
Public class Treadapp {//volatile thread sharing variables between threads
private static Volatile Boolean Isexit=false;//static member cannot access non-static members
Public static void Main (string[] args) {
//Download a file to start the thread, use the thread pool,
//Start thread download file 1. Thread Implementation Method
//multi-line Comment shift+ctrl+/
/ * 1. New Downloadtread ("File1"). Start ();
new Downloadtread ("File2"). Start ();
new Downloadtread ("File3"). Start ();
new Downloadtread ("File4"). Start (); */
/ * 2. New Thread ((New Downloadtask ("File1")). Start ();
New Thread ((New Downloadtask ("File2")). Start ();
New Thread ((New Downloadtask ("File3")). Start ();
New Thread ((New Downloadtask ("File4")). Start ();
New Thread ((New Downloadtask ("File5")). Start (); */
New Thread ((New Downloadtask ("File1")). Start ();
//main thread hibernation 2s execution exit
try {
Thread.Sleep (Long.parselong (")");
} catch (Interruptedexception e) {
e.printstacktrace ();
}
//print main thread ID
System.out.println ("Current main thread ID:" +thread.currentthread (). GetId ());
isexit=true;
//4. New Thread () {//can be called directly by thread
//@Override
//public void Run () {
//Super.run ();
// }}. Start ();
}
Static class Downloadtask implements runnable{
private String URL;
private int currentthreadid=-1;
Public downloadtask (String url) {
This.url=url;
}
@Override
Public void Run () {
//Gets the ID of the current thread
//Thread.CurrentThread (). GetId ()
currentthreadid = (int) thread.currentthread (). GetId ();
System.out.println ("Download ..." +url+ ", Thread ID:" +currentthreadid+ "start");
//Random generation of 5-10s
int s= (int) (Math.random () *6+5);//[5,10]
for (int i = 0; I <s; i++) {
try {
Thread.Sleep (Long.parselong (") ");
} catch (Interruptedexception e) {
e.printstacktrace ();
}
if (isexit)
return;
System.out.println (currentthreadid+ "used ..." +i+ "seconds");
}
System.out.println (currentthreadid+ "Download Complete" +url);
}
}
//Member inner class of class
Static class Downloadtread extends Thread {
private String url;//file path
Public downloadtread (String url) {
this.url = URL;
}
Public void Run () {
Super.run ();//no function no effect
//Implement download file code
Unique identification of the//Thread.getid () line thread
System.out.println ("Downloading file" + URL + "Thread ID:" + getId ());
int ms = (int) (Math.random () * 11 + 2) * 1000;//2-12 milliseconds
System.out.println (URL + "scheduled time to complete" + ms/1000 + "seconds");
try {
sleep (MS);//thread hibernation
} catch (Interruptedexception e) {
e.printstacktrace ();
}
System.out.println (url + "file has been downloaded to complete!) ");
}
}
}
treadapp-using threads to download files