火车站卖票:
public class TicketDemo extends Thread {
static int count = 20;
static String a = "";
@Override
public void run() {
while (true) {
try {
//睡眠时间:循环一次,睡眠一次 -- 单位:mm
Thread.sleep(2000);
synchronized (a) {
if (count > 0) {
System.out.println("第" + count + "张票");
count--;
} else {
System.out.println("卖完了");
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TicketDemo td = new TicketDemo();
td.start();
TicketDemo td1 = new TicketDemo();
td1.start();
}
}
文件下载
public class DownLoad extends Thread{
private int startIndex; //线程开始下载位置
private int endIndex; //线程结束下载位置
private int threadId; //线程编号
public DownLoad(int startIndex, int endIndex, int threadId) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
try {
//统一资源管理器 ,可以直接打开 网络地址
URL url = new URL(DownLoadTest.path);
//获取网络请求
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置一些参数
conn.setRequestMethod("GET");//请求方式
conn.setConnectTimeout(5000);//链接超时
conn.setReadTimeout(5000);//读取超时
conn.setRequestProperty("Range","bytes="+startIndex+"-"+endIndex);//获取线程下载范围
if(conn.getResponseCode()==206){//如果状态码为206,则显示部分数据下载完成
//取出下载完成的链接中的数据
InputStream is = conn.getInputStream(); //这个里面存储的是服务器上百度客户端数据
//本地接受
File fi = new File("BaiduNetdisk_6.9.7.4.exe");
//输出流 ---使用的是随机读写流 rwd
RandomAccessFile raf = new RandomAccessFile(fi,"rwd");
//跳转到每个线程开始读取的地方
raf.seek(startIndex);
System.out.println("线程:"+threadId+"开始的位置"+startIndex+"--结束位置"+endIndex);
int i = 0;
byte[] bytes = new byte[1024];
while ((i=is.read(bytes))!=-1){
raf.write(bytes,0,i);
}
System.out.println("下载完毕");
raf.close();
DownLoadTest.finishedThread ++;
//如果全部下载完毕,则让finishedThread为0
synchronized (DownLoadTest.path){
DownLoadTest.finishedThread=0;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class DownLoadTest {
static String path = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";
static int threadCount = 3; //3个线程
static int finishedThread = 0; //和 线程数 有关 ,记录每一个线程是否执行完毕
public static void main(String[] args) {
try {
//打开网络地址
URL url = new URL(DownLoadTest.path);
//获取网络对象,与网络建立链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置一些网络参数
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if(conn.getResponseCode() == 200){
//拿到文件
int contentLength = conn.getContentLength();
//每个线程下载的大小
int size = contentLength/threadCount;
//开启线程下载
for (int i = 0; i < threadCount; i++) {
int startIndex = i*size;//每个线程的开始位置
int endIndex = (i+1)*size;//每个线程的结束位置
DownLoad dl = new DownLoad(startIndex,endIndex,i);
dl.start();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}