线程中run方法会被同步吗?
各位帮忙看看下面的代码,main方法中产生了几个线程,为什么?如果是多个线程,查看程序的运行结果,好像这个run方法被同步了啊?为什么啊。好像在后面三个线程中始终都无法访问index。
public class Interfacaesharethread {
public static void main(String[] args) {
Mythread1 mythread = new Mythread1();
Thread t1 = new Thread(mythread);
t1.start();
System.out.println(t1.getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t2 = new Thread(mythread);
t2.start();
System.out.println(t2.getName());
Thread t3 = new Thread(mythread);
t3.start();
System.out.println(t3.getName());
Thread t4 = new Thread(mythread);
t4.start();
System.out.println(t4.getName());
}
}
class Mythread1 implements Runnable {
int index = 0;
public synchronized void run() {
System.out.println("in to Thread");
while (index<10){
System.out.println(Thread.currentThread().getName()
+ "is running and the index is " + index++);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("out of Thread " + Thread.currentThread().getName());
}
}