[size=large]代码例子:[/size]
package com.test;
public class ThreadTest3
{
public static void main(String[] args)
{
Runnable r = new HelloThread();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
class HelloThread implements Runnable
{
//int i;//多个线程对同一个对象的成员变量操作时,一个线程对成员变量改变,会影响另外一个线程
public void run()
{
int i = 0;//多个线程对同一个对象的局部变量操作时,一个线程对局部变量改变,不会影响另外一个线程
while (true)
{
System.out.println("number:" + i++);
try
{
Thread.sleep((long)(Math.random()*1000));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if(50 == i)
{
break;
}
}
}
}
9262

被折叠的 条评论
为什么被折叠?



