New example and unit test
This commit is contained in:
parent
1aa2f849f4
commit
159461815d
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.concurrent.synchronizestatic.synchronizedclass;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronizing static variable with a synchronized block.
|
||||||
|
*/
|
||||||
|
public class Employee
|
||||||
|
{
|
||||||
|
static int count;
|
||||||
|
int id;
|
||||||
|
String name;
|
||||||
|
String title;
|
||||||
|
|
||||||
|
public Employee(int id, String name, String title)
|
||||||
|
{
|
||||||
|
incrementCount();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void incrementCount() {
|
||||||
|
synchronized(Employee.class) {
|
||||||
|
System.out.println("Count = " + ++count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int getCount() {
|
||||||
|
synchronized(Employee.class) {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -45,10 +45,24 @@ public class SychronizeStaticDataUnitTest
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSynchronizedClass_thenDataInOrder() {
|
||||||
|
|
||||||
|
System.out.println("Synchronization with synchronized block on class");
|
||||||
|
|
||||||
|
for(int i = 0; i < numberToTest; i++) {
|
||||||
|
int finalI = i;
|
||||||
|
pool.execute(() ->
|
||||||
|
{
|
||||||
|
new com.baeldung.concurrent.synchronizestatic.synchronizedclass.Employee(finalI, "John", "Smith");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSynchronizedBlock_thenDataInOrder() {
|
public void whenSynchronizedBlock_thenDataInOrder() {
|
||||||
|
|
||||||
System.out.println("Synchronization with synchronized block");
|
System.out.println("Synchronization with synchronized block on a private object");
|
||||||
|
|
||||||
for(int i = 0; i < numberToTest; i++) {
|
for(int i = 0; i < numberToTest; i++) {
|
||||||
int finalI = i;
|
int finalI = i;
|
||||||
|
|
Loading…
Reference in New Issue