Example - String print


class TwoStrings {
     void print(String str1,String str2) {
        System.out.print(str1);
        try {
            Thread.sleep(50);
        } catch (InterruptedException ie) {        }
        System.out.println(str2);
    }
}

class PrintStringsThread extends Thread {
     String str1, str2;
     TwoStrings ts;
     PrintStringsThread(String str1, String str2,     TwoStrings ts) {
        this.str1 = str1;
        this.str2 = str2;
        this.ts = ts;
        this.start(); 
    }
    public void run() {
            ts.print(str1, str2);
    }
}

public class App {
    public static void main(String args[]) {
         TwoStrings ts = new TwoStrings();
        new PrintStringsThread("Hello ", "there.",ts);
        new PrintStringsThread("How are ", "you?",ts);
        new PrintStringsThread("Thank you ", "very much!",ts);
    }
}
How are Hello Thank you there.
you?
very much!

 

Synchronized method

class TwoStrings {
synchronized void print(String str1,String str2) {
System.out.print(str1);
try {
Thread.sleep(50);
} catch (InterruptedException ie) { }
System.out.println(str2);
}
}

class PrintStringsThread extends Thread {
String str1, str2;
TwoStrings ts;
PrintStringsThread(String str1, String str2, TwoStrings ts) {
this.str1 = str1;
this.str2 = str2;
this.ts = ts;
this.start();
}
public void run() {
ts.print(str1, str2);
}
}

public class App {
public static void main(String args[]) {
TwoStrings ts = new TwoStrings();
new PrintStringsThread("Hello ", "there.",ts);
new PrintStringsThread("How are ", "you?",ts);
new PrintStringsThread("Thank you ", "very much!",ts);
}
}
Hello there.
Thank you very much!
How are you?

 

 
Synchronized object

class TwoStrings {
void print(String str1,String str2) {
System.out.print(str1);
try {
Thread.sleep(50);
} catch (InterruptedException ie) { }
System.out.println(str2);
}
}

class PrintStringsThread extends Thread {
String str1, str2;
TwoStrings ts;
PrintStringsThread(String str1, String str2, TwoStrings ts) {
this.str1 = str1;
this.str2 = str2;
this.ts = ts;
this.start();
}
public void run() {
synchronized (ts) {
ts.print(str1, str2);
}
}
}

public class App {
public static void main(String args[]) {
TwoStrings ts = new TwoStrings();
new PrintStringsThread("Hello ", "there.",ts);
new PrintStringsThread("How are ", "you?",ts);
new PrintStringsThread("Thank you ", "very much!",ts);
}
}
Hello there.
How are you?
Thank you very much!