xiaoliang330 发表于 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
谢谢学长
页: [1]
查看完整版本: 关于线程----线程间的数据共享