同一条线似乎是';它运行两次,但在Java中只调用一次
我的主目录下有以下代码: MyThread类如下所示:同一条线似乎是';它运行两次,但在Java中只调用一次,java,multithreading,synchronized,java-threads,Java,Multithreading,Synchronized,Java Threads,我的主目录下有以下代码: MyThread类如下所示: public class MyThread implements Runnable { private static int threadCounter=0; private int myThreadId=0; @Override public void run() { synchronized(Lock.lock){ threadCounter++;
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已创建线程
主要已完成运行的文件
运行()
runMe()
线程1已启动
螺纹1已完成
8
线程2已启动
螺纹2已完成
八, 我很难理解为什么会发生这样的事情。
很明显(至少对我来说)只创建了一次线程(只有一次我们可以看到运行(),运行()和线程被创建),但是两次线程开始/完成和输出中的线程ID。
为什么线程计数器会增加两次,而只输入run()一次
另外,我正在使用Java6。您缺少
break代码>在案例1
和案例2
之后,您缺少中断在案例1
和案例2
之后添加code>
public class Lock {
public static final Lock lock=new Lock();
public static final int totalThreads=1;
}