相同的线程似乎正在运行两次,但只在Java中调用一次

时间:2015-10-27 20:05:16

标签: java multithreading synchronized java-threads

我的 main 下面有以下代码:

System.out.println(Thread.currentThread().getId());  
for(inti=0;i!=Lock.totalThreads;i++) {  
    System.out.println("thread wascreated");   
    (new Thread(new MyThread())).start();   
}
System.out.println("main finished running files");

MyThread 类如下所示:

public class MyThread implements Runnable {
    private static int threadCounter=0;
    private int myThreadId=0;
    @Override
    public void run() {
        synchronized(Lock.lock){
            threadCounter++;
            myThreadId=threadCounter;
        }
        System.out.println("run()");
        try {
            runMe();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void runMe() throws IOException, InterruptedException {
        String currentFile;
        BufferedReader in;
        System.out.println("run()");
        switch(myThreadId){
        case 1:
            System.out.println("thread1 started");
            System.out.println("thread1 finished");
            System.out.println(Thread.currentThread().getId());
        case 2: 
            System.out.println("thread2 started");
            System.out.println("thread2 finished");
            System.out.println(Thread.currentThread().getId());

        }
    }

Lock 类看起来像这样:

public class Lock {
    public static final Lock lock=new Lock();
    public static final int totalThreads=1;
}

控制台输出如下:

  

1
  线程创建了   主要完成运行文件
  的run()
  邵仁枚()
  thread1开始了   thread1完成了   8
  thread2开始了   thread2完成了   8

我很难理解这样的事情是怎么发生的 很明显(至少对我来说)只创建一次Thread(只有一次我们可以看到 run() runMe()线程已创建),但输出中有两次主题开始/结束主题ID
 为什么 threadCounter 增加两次,而只输入run()一次?

P.S,我正在使用Java 6.

1 个答案:

答案 0 :(得分:12)

break;case 1后,您遗漏了case 2