Java — Synchronization Method | Code Factory

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 synchronized void wish(String name) {
for(int i=0; i<5; i++) {
System.out.print("Display ");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(name);
}
}
}
class MyThread extends Thread {
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.wish(name);
}
}
Display Code
Display Code
Display Code
Display Code
Display Code
Display Factory
Display Factory
Display Factory
Display Factory
Display Factory
package com.example.thread;/**
* @author code.factory
*
*/
public class SynchronizedTest {
public static void main(String... args) {
Display d1 = new Display();
Display d2 = new Display();
MyThread t1 = new MyThread(d1, "Code");
MyThread t2 = new MyThread(d2, "Factory");
t1.start();
t2.start();
}
}
class Display {
public synchronized void wish(String name) {
for(int i=0; i<5; i++) {
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(name);
}
}
}
class MyThread extends Thread {
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.wish(name);
}
}
Code
Factory
Code
Factory
Factory
Code
Code
Factory
Code
Factory

--

--

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