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

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>


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

弄个例子说明一下

点击打开链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值