Though one wonders why this is necessary, here is one way to do it. It is not elegant but represents a minimal change to the original program:
import java.util.concurrent.*;
public class TestSync {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
service.submit(new Thread1());
}
}
public int getNum(int i) {
synchronized (this) {
i++;
}
return i;
}
static class Thread1 implements Runnable {
static Integer value = 0;
@Override
public void run() {
TestSync ts = new TestSync();
value = ts.getNum(value);
System.out.println("thread1:" + value);
}
}
}
Here is a version that is better. It uses an AtomicInteger for the counter (which is probably overkill in this case) to remove the unpleasant getNum() method:
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class TestSync {
static private AtomicInteger i = new AtomicInteger(0);
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
service.submit(new MyThread(i));
}
try { Thread.sleep(2*1000); } catch(Exception ex) {}
service.shutdown();
}
static class MyThread implements Runnable {
private int num = 0;
public MyThread(int num) {
this.num = num;
}
@Override
public void run() {
int value = i.incrementAndGet();
System.out.println("thread # " + num + " value = " + value);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…