六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 55|回复: 0

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

[复制链接]

升级  11.33%

15

主题

15

主题

15

主题

秀才

Rank: 2

积分
67
 楼主| 发表于 2013-1-19 04:07:19 | 显示全部楼层 |阅读模式
当多个线程的执行代码来自同一个类的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
谢谢学长
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表