class DownLoadThread extends Thread{
int start;
int end;
DownLoadThread(int start,int end){
this.start = start;
this.end = end;
}
@Override
public void run() {
while(start <= end){
System.out.println(Thread.currentThread().getName()+":"+start++);
/*try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
}
public class TestDown {
public static void main(String[] args) {
int size = 100;
int threadCount = 3;
int blockSize = size / threadCount;
for(int i=1;i<=threadCount;i++){
int startIndex = (i-1)*blockSize;
int endIndex = i*blockSize-1;
if(i == threadCount){
endIndex = size;
}
System.out.println(i+":"+startIndex+"-->"+endIndex);
new DownLoadThread(startIndex,endIndex).start();
}
}
}
在主函数中用for循环创建三个线程,并传入构造函数的参数
这其中
DownLoadThread是<span style="font-family: Arial, Helvetica, sans-serif;">extends</span>继承了Thread <span style="font-family: Arial, Helvetica, sans-serif;">当然</span><span style="font-family: Arial, Helvetica, sans-serif;">implements</span><span style="font-family: Arial, Helvetica, sans-serif;">实现Runnable也是可以的</span>
<span style="font-family: Arial, Helvetica, sans-serif;">这里在重载run函数实现数据共享。</span>
但是有好多地方要使用线程,有没有想过为什么要使用他难道仅仅是一个共享数据这显然不对
弄个例子说明一下