-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreads_sync.java
More file actions
48 lines (39 loc) · 1.13 KB
/
Copy pathThreads_sync.java
File metadata and controls
48 lines (39 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* This is a sample main program to show how to use the
* synchronized keyword to prevent multiple threads from
* corrupting our data
*/
/*
- Synchronized can be applied to methods or code blocks
*/
public class Threads_sync {
//define a class variable called counter
static int counter = 1;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException {
/* Example of locking using a synchronized method */
// Runnable r = () -> {
// System.out.println("ID value: " + getID());
// };
// Thread one = new Thread(r,"one");
// one.start();
// Thread two = new Thread(r,"two");
// two.start();
// }
/* Example of locking using an object */
Runnable r2 = () -> {
ID id = new ID();
System.out.println("ID value: "+id.getID());
};
Thread one = new Thread(r2,"one");
one.start();
Thread two = new Thread(r2,"two");
two.start();
// }
public static synchronized int getID()
{
return counter++;
}
}