关于线程----线程间的数据共享

当多个线程的执行代码来自同一个类的run方法,既称他们共享相同的代码;当共享访问相同的对象时,既他们共享相同的数据。



演示代码

Java代码
import java.lang.*;

public class Demo
{
public static void main(String[] args)
{
MyThread thread=new MyThread();
new Thread(thread,"A").start();
new Thread(thread,"B").start();
new Thread(thread,"C").start();
}
}

class MyThread implements Runnable
{
private int sleepTime;
public MyThread()
{
sleepTime=(int)(Math.random()*6000); //获得随机休眠毫秒数
}

public void run()
{
try
{
System.out.println(Thread.currentThread().getName()+"要休息"+sleepTime+"ms");
Thread.sleep(sleepTime);
System.out.println(Thread.currentThread().getName()+"睡醒了。");
}
catch(Exception e)
{
System.out.println(Thread.currentThread().getName()+"被吵醒了!");
}
}
}

import java.lang.*;

public class Demo
{
public static void main(String[] args)
{
MyThread thread=new MyThread();
new Thread(thread,"A").start();
new Thread(thread,"B").start();
new Thread(thread,"C").start();
}
}

class MyThread implements Runnable
{
private int sleepTime;
public MyThread()
{
sleepTime=(int)(Math.random()*6000); //获得随机休眠毫秒数
}

public void run()
{
try
{
System.out.println(Thread.currentThread().getName()+"要休息"+sleepTime+"ms");
Thread.sleep(sleepTime);
System.out.println(Thread.currentThread().getName()+"睡醒了。");
}
catch(Exception e)
{
System.out.println(Thread.currentThread().getName()+"被吵醒了!");
}
}
}

运行结果

输出结果代码
A要休息5299ms
B要休息5299ms
C要休息5299ms
//漫长的等待
C睡醒了。
A睡醒了。
B睡醒了。

A要休息5299ms
B要休息5299ms
C要休息5299ms
//漫长的等待
C睡醒了。
A睡醒了。
B睡醒了。

可见,因为是用一个Runnable类型的对象创建的三个新线程,这三个线程就共享了这个对象的私有成员sleepTime变量,在本次运行中,三个线程都休眠了5299毫秒。

以上内容摘自http://coolszy.iteye.com/blog/485765
谢谢学长
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值