java - 同一个线程看起来好像运行了两次,但在 Java 中只调用了一次

标签 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
thread was created
main finished running files
run()
runMe()
thread1 started
thread1 finished
8
thread2 started
thread2 finished
8

我很难理解为什么会发生这样的事情。
很明显(至少对我而言)只有一次线程被创建(只有一次我们可以看到 run()runMe()thread 是已创建),但两次thread started/finished 和输出中的Thread ID
为什么 threadCounter 递增两次,而只进入 run() 一次?

附言,我使用的是 Java 6。

最佳答案

case 1case 2 之后都缺少 break;

关于java - 同一个线程看起来好像运行了两次,但在 Java 中只调用了一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377464/

相关文章:

java - 使用 Selenium 和 Java 获取链接文本

c++ - Boost单元测试可以多线程吗?

Python 和 C/C++ 多线程 : run several threads executing python in the background of C

java - 多线程

javascript - 在客户端检测时区

java - 什么时候在 Java 中使用 printf 语句?

php - 使用 Javascript ajax 在 PHP 中实现多线程,可能吗?

java - 同步静态方法在 android 中不起作用?

java - wait() 和 notify() JMM 语义

java - CentOS 5.5下SeleniumGrid的init.d脚本