Created
January 3, 2014 09:35
-
-
Save buptpatriot/8235359 to your computer and use it in GitHub Desktop.
Test Java Synchronization.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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