Java中的多线程共享同一个成员变量,拥有不同的局部变量。
public class ThreadTest {
public static void main(String[] args) {
Runnable r = new Skyritx();
Thread thread1 = new Thread(r);
Thread thread2 = new Thread(r);
thread1.start();
thread2.start();
}
}
class Skyritx implements Runnable{
int i;
public void run()
{
i = 0;
while(true)
{
System.out.println("number: " + i++);
try {
Thread.sleep((long)(Math.random() * 1000));
}
catch (InterruptedException e) {
e.printStackTrace();
}
if(i == 50)
break;
}
}
}
试比较在不同位置定义i的效果。