==
package Demo5;
/**
* Title -- Advanced Java_ Multi-threading Part 3 -- The Synchronized Keyword
* Note:-- Basic Thread synchronization
* @author Bapa
* Every object in java has a intransit lock one thread can aquare at a time lock of an object.
*/
public class App {
private int count = 0;
public synchronized void increement() {
count++;
}
public static void main(String[] args) {
App app = new App();
app.doWork();
}
public void doWork() {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
increement();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
increement();
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count is " + count);
}
}
No comments:
Post a Comment