package main;
/**
* Created by lxj-pc on 2017/6/27.
*/
public class TreadApp {//volatile 线程间共享变量
private static volatile boolean isExit=false;//static成员不能访问非static成员
public static void main(String[] args) {
//下载一个文件 启动线程 ,线程池使用,
//启动线程 下载文件 1.线程自己实现方法
//多行注释 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();
//主线程休眠2s 执行退出
try {
Thread.sleep(Long.parseLong("2000"));
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印主线程ID
System.out.println("当前主线程ID:"+Thread.currentThread().getId());
isExit=true;
// 4. new Thread(){//可以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() {
//获取当前线程的ID
// Thread.currentThread().getId()
currentThreadId = (int) Thread.currentThread().getId();
System.out.println("下载..."+url+",线程ID:"+currentThreadId+"开始");
//随机产生5-10s
int s= (int) (Math.random()*6+5); // [5,10]
for (int i = 0; i <s ; i++) {
try {
Thread.sleep(Long.parseLong("1000"));
} catch (InterruptedException e) {
e.printStackTrace();
}
if(isExit)
return;
System.out.println(currentThreadId+"已用.."+i+ "秒");
}
System.out.println(currentThreadId+"下载完成"+url);
}
}
//类的成员内部类
static class DownloadTread extends Thread {
private String url;//文件路径
public DownloadTread(String url) {
this.url = url;
}
public void run() {
super.run();//无功能 无作用
//实现下载文件代码
// Thread.getId() 线程里的唯一标识
System.out.println("正在下载文件" + url + "线程id:" + getId());
int ms = (int) (Math.random() * 11 + 2) * 1000;//2-12毫秒
System.out.println(url + "计划完成时间" + ms / 1000 + " 秒");
try {
sleep(ms);//线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(url + "文件已经下载完成!");
}
}
}