// 本程序用来说明 类的实例中的私有成员是否线程安全
public class Zy_thread_test1
{
public static void main(String[] args)
{
hello tHello=new hello(); //这里创建一个对象
for(int j=0;j<5;++j)
{
/****************************************************************
(1)new Thread( tHello )建立的每个线程,都运行了tHello对象的run方法,所以这些线程都可以操作 tHello对象 的私有成员i,
所以 tHello对象 的私有成员i不是线程安全的
(2)将new Thread( tHello ).start() 改成 new Thread( new hello() ).start();那么每个线程都运行一个新建实例的run方法,
这时 每个线程的run方法操作的是自己实例中的私有成员i,每个实例的私有成员i互不干扰,是线程安全的
***************************************************************/
new Thread( tHello ).start();
// new Thread( new hello() ).start();
System.out.println("==================== " + j + " start ==========================" );
}
}
}
class hello implements Runnable
{
private int i=0; // 私有成员,可能是线程安全,也可能是不安全的
//public static int i=0; //类的静态变量一定是线程不安全的
public void run()
{
//int i=0; //方法内的局部变量一定是线程安全的
while(i<100)
{
try {
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
i++;
System.out.println( Thread.currentThread().getName() +" --- "+ i );
}
}
}