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

Ach*_*dar 1 java multithreading synchronized java-threads

我的主要内容下面有以下代码:

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");
Run Code Online (Sandbox Code Playgroud)

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());

        }
    }
Run Code Online (Sandbox Code Playgroud)

类如下所示:

public class Lock {
    public static final Lock lock=new Lock();
    public static final int totalThreads=1;
}
Run Code Online (Sandbox Code Playgroud)

控制台输出是这样的:

1个
线程被创建
主要完成运行文件
run()
runMe()
thread1启动
thread1完成
8个
thread2启动
thread2完成
8个

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

PS,我使用的是Java 6.

Zby*_*000 12

你和break;两个都失踪了.case 1case 2

  • 并默认:) (3认同)