1synchronized blocks the next thread's call to method
2 as long as the previous thread's execution is not finished.
3 Threads can access this method one at a time.
4 Without synchronized all threads can access this method simultaneously.
1The synchronized keyword is all about different threads reading and writing
2to the same variables, objects and resources.
1public class MyCounter {
2
3 private int count = 0;
4
5 public synchronized void add(int value){
6 this.count += value;
7 }
8}
9
1class First
2{
3 synchronized public void display(String msg)
4 {
5 System.out.print ("["+msg);
6 try
7 {
8 Thread.sleep(1000);
9 }
10 catch(InterruptedException e)
11 {
12 e.printStackTrace();
13 }
14 System.out.println ("]");
15 }
16}
17
18class Second extends Thread
19{
20 String msg;
21 First fobj;
22 Second (First fp,String str)
23 {
24 fobj = fp;
25 msg = str;
26 start();
27 }
28 public void run()
29 {
30 fobj.display(msg);
31 }
32}
33
34public class MyThread
35{
36 public static void main (String[] args)
37 {
38 First fnew = new First();
39 Second ss = new Second(fnew, "welcome");
40 Second ss1= new Second(fnew,"new");
41 Second ss2 = new Second(fnew, "programmer");
42 }
43}
44