我有以下代码:
public class MyApp {
public static void main(String[] args) throws InterruptedException {
SharedResource sharedResource = new SharedResource();
Runnable first = () -> {
sharedResource.increment(10000);
};
Runnable second = () -> {
sharedResource.increment(10000);
};
Thread thread = new Thread(first, "FirstThread");
Thread thread2 = new Thread(second, "SecondThread");
thread.start();
thread2.start();
thread.join();
thread2.join();
System.out.println("The value of counter is " + sharedResource.getCounter());
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个类:
public class SharedResource {
private int counter;
public void increment(int times) {
for (int x=1; x<=times;x++) {
counter++;
// …Run Code Online (Sandbox Code Playgroud)