我的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 1
和 case 2
之后都缺少 break;
。
关于java - 同一个线程看起来好像运行了两次,但在 Java 中只调用了一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377464/