- /**
- * Java - the synchronized keyword
- * Sometimes, you only want to prevent multiple thread access to part of the code inside a method instead of the entire method.
- * The section of code you want to isolate this way is called 'critical section' and is created using the synchronized keyword.
- */
- class ClassA
- {
- private static int id = 0;
- public void getId(String threadName)
- {
- /**
- * Here, synchronized is used to specify the object whose lock is being used to synchronize the enclosed code.
- * This is also called a synchronized block; before it can be entered, the lock must be acquired a lock on a object.
- * If some other task already has his lock, then the critical section cannot be entered until the lock is released.
- */
- synchronized (this/* an object here */)
- {
- id++;
- try
- {
- Thread.sleep(1);
- } catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- System.out.println("thread name: " + threadName + "\n" + "id: " + id);
- }
- }
- }
- public class Main implements Runnable
- {
- public static void main(String[] args)
- {
- Main m1 = new Main();
- Main m2 = new Main();
- Thread t1 = new Thread(m1);
- Thread t2 = new Thread(m2);
- t1.start();
- t2.start();
- }
- @Override
- public void run()
- {
- try
- {
- new ClassA().getId(Thread.currentThread().getName());
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }