您的位置:首页 > 其它

关于多线程共享数据的一些疑惑

2015-06-18 15:39 337 查看
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>


但是有好多地方要使用线程,有没有想过为什么要使用他难道仅仅是一个共享数据这显然不对

弄个例子说明一下

点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 thread