创建多线程时,如果使用同一个runnable对象,则多个线程共享一个runnable资源
<pre name="code" class="java">public class MyThread implements Runnable {
int i;
@Override
public void run() {
while(true){
try {
Thread.sleep((long)Math.random()*1000);
System.out.println(Thread.currentThread().getName()+i++);
} catch (InterruptedException e) {
e.printStackTrace();
}
if( i == 20)
break;
}
}
}
public class ThreadTest {
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt,"1:");
Thread t2 = new Thread(mt,"2:");
t1.start();
t2.start();
}
}
运行结果如下图: