Skip to content

Instantly share code, notes, and snippets.

@buptpatriot
Created January 3, 2014 09:35
Show Gist options
  • Save buptpatriot/8235359 to your computer and use it in GitHub Desktop.
Save buptpatriot/8235359 to your computer and use it in GitHub Desktop.
Test Java Synchronization.
import java.lang.Thread;
import java.util.concurrent.atomic.AtomicInteger;
public class TestSynchronization {
public static void main(String[] args) {
Task task = new Task();
for (int i = 0; i < 100; i++) {
new Thread(task).start();
}
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// task.printNum();
task.printNum2();
}
}
class Task implements Runnable {
private int num = 0;
private AtomicInteger num2 = new AtomicInteger(0);
public synchronized void inc() {
num++;
}
public void inc2() {
num2.getAndIncrement();
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
// inc();
inc2();
}
System.out.println("finish");
}
public void printNum() {
System.out.println("num : " + num);
}
public void printNum2() {
System.out.println("num2 : " + num2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment