我刚开始接触线程编程,写了一个简单的程序来测试如何避免竞态条件。我的第一次尝试是使用命名内部类:
/* App1.java */
package ehsan;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App1{
private final int poolSize = 10;
private final int numLoop = 5;
private int lastThread = 0;
public App1() {
ExecutorService taskList = Executors.newFixedThreadPool(poolSize);
for (int i = 0;i < poolSize;i++) {
taskList.execute(new Counter());
}
taskList.shutdown();
}
private class Counter implements Runnable{
@Override
public void run() {
synchronized (this) {
int currentThread = lastThread;
System.out.println("Current thread : "+currentThread);
lastThread = lastThread + 1;
}
System.out.println("Thread was executed");
}
}
}
以及 App1Test.java
:
package ehsan;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
new App1();
}
}
因此,它显示了:
Current thread : 0
Thread was executed
Current thread : 1
Thread was executed
Current thread : 1
Thread was executed
Current thread : 3
Thread was executed
Current thread : 4
Thread was executed
Current thread : 5
Thread was executed
Current thread : 6
Thread was executed
Current thread : 7
Thread was executed
Current thread : 6
Current thread : 8
Thread was executed
Thread was executed
我的事情全都搞混了,即使我已经使用了synchronized
,我仍然面临竞态条件。
但是我的第二次尝试成功了!:
package ehsan;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App1 implements Runnable{
private final int poolSize = 10;
private final int numLoop = 5;
private int lastThread = 0;
public App1() {
ExecutorService taskList = Executors.newFixedThreadPool(poolSize);
for (int i = 0;i < poolSize;i++) {
taskList.execute(this);
}
taskList.shutdown();
}
@Override
public void run() {
synchronized (this) {
int currentThread = lastThread;
System.out.println("Current thread : "+currentThread);
lastThread = lastThread + 1;
System.out.println("Thread was executed");
}
}
}
结果与我预期的一样:
Current thread : 0
Thread was executed
Current thread : 1
Thread was executed
Current thread : 2
Thread was executed
Current thread : 3
Thread was executed
Current thread : 4
Thread was executed
Current thread : 5
Thread was executed
Current thread : 6
Thread was executed
Current thread : 7
Thread was executed
Current thread : 8
Thread was executed
Current thread : 9
Thread was executed
所以我的问题是为什么我的第一次尝试没有成功,而第二次尝试非常成功?谢谢你的帮助,我是多线程编程的初学者!
run()
方法几乎总是一个错误。在您的第二个“工作”示例中,synchronized
块防止任何一个线程与其同行同时运行。但是,如果您不允许线程同时运行,那么使用线程的意义何在? - Solomon Slow