Java — Synchronization Block | Code Factory

synchronized(this) {
---
}
of a thread got lock of current object then only it is called to execute this(---) area.
synchronized(b) {
---
}
of a thread got lock of particular object 'a' then only it is allowed to execute this(---) area.
synchronized(Display.class) {
---
}
of a threat got class level lock of Display class, then only it is allowed to execute this(---) area.
package com.example.thread;/**
* @author code.factory
*
*/
public class SynchronizedTest {
public static void main(String... args) {
Display d = new Display();
MyThread t1 = new MyThread(d, "Code");
MyThread t2 = new MyThread(d, "Factory");
t1.start();
t2.start();
}
}
class Display {
public void display(String name) {
// lines of code
synchronized (this) {
for(int i=1; i<=5; i++) {
System.out.print("Hello ");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(name);
}
}
// lines of code
}
}
class MyThread extends Thread {
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.display(name);
}
}
Hello Code
Hello Code
Hello Code
Hello Code
Hello Code
Hello Factory
Hello Factory
Hello Factory
Hello Factory
Hello Factory
int i = 10;
synchronized(x) {
---
}
CE :
error: unexpected type
synchronized (i) {
^
required: reference
found: int
1 error

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store