各位帮忙看看下面的代码,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());
}
}

解决方案 »

  1.   

    run方法没有同步只是应为
    t1.start();
    System.out.println(t1.getName());
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    第一个线程被启动以后主线程睡了两秒,等到再启动后面的线程以后第一个线程早就结束了
      

  2.   

    楼上的不妨把
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    去掉再看看。
    再请问如果是多个线程,各个线程中的同步方法会相互影响吗?
      

  3.   

    run方法是被同步了,因为关键词:synchronized。
    class Mythread1 implements Runnable {
    int index = 0;public synchronized void run() {     //run方法中的关键词:synchronized 
    System.out.println("in to Thread");
    .....