【问题标题】:Same thread seems as if it's running twice but is only invoked once in Java同一个线程似乎运行了两次,但在 Java 中只调用了一次
【发布时间】:2016-01-27 10:11:14
【问题描述】:

我的 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
线程已创建
主要完成运行文件
运行()
运行我()
线程 1 已启动
线程1完成
8
线程 2 已启动
线程2完成
8

我很难理解为什么会发生这样的事情。
很明显(至少对我来说)只有一次线程被创建(只有一次我们可以看到 run()runMe()thread创建),但两次线程启动/完成和输出中的线程ID
为什么 threadCounter 增加了两次,而进入 run() 只一次?

P.S,我使用的是 Java 6。

【问题讨论】:

    标签: java multithreading synchronized java-threads


    【解决方案1】:

    case 1case 2 之后,您缺少break;

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2015-04-07
      • 2016-10-20
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多