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

来源:互联网 发布:阿里云学生认证失败 编辑:程序博客网 时间:2024/05/17 01:01
class DownLoadThread extends Thread{int start;int end;DownLoadThread(int start,int end){this.start = start;this.end = end;}@Overridepublic void run() {while(start <= end){System.out.println(Thread.currentThread().getName()+":"+start++);/*try {Thread.sleep(30);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.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>


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

弄个例子说明一下

点击打开链接


0 0
原创粉丝点击