Втори пример - отпечатване на два низа

Без синхронизация

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!

 

Синхронизация с заключване на метод:

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?

 

 
Синхронизация с заключване на общ обект

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!

 

Пример:  Еднопосочен мост с коли идващи от двете посоки

мост - ресурс за ползване от колите:

public class Bridge {
    private int nVh;
    Bridge(){
        nVh = 0;
    }
    synchronized public int brN(){
        return nVh;
    }
    synchronized public void takeB(boolean lr ){
        while((nVh>0)&& (lr==true)||
              (nVh<0) && (lr==false)){
            System.out.println("\t"+Thread.currentThread().getName()+" waiting");
            try{     wait();   }
            catch(InterruptedException e){
                System.err.println(e);
            }
        }
        if (lr) nVh--;
        else nVh++;
        System.out.println(Thread.currentThread().getName()+" on the bridge");
    }
    synchronized public void leaveB(boolean lr ){
        if (nVh>0) nVh--;
        else nVh++;
        System.out.println("\t\t"+Thread.currentThread().getName()+" leave the bridge");
        notifyAll();
    }
}

коли - нишки

public class Vehicle extends Thread{
    boolean lr;
    Bridge b;
    String name;
    static int num;
    Vehicle(boolean lr, Bridge b){
        this.lr=lr;
        this.b = b;
        name = "V "+ ++num + (lr?" left->":" <-right");
        super.setName(name);
    }
    public void run(){
        b.takeB(lr);
        try {
            sleep((int)(Math.random()*200));
        } catch (InterruptedException e){} 
        b.leaveB(lr);
    }
}

Самият модел:

public class Circ {
    public static void main(String arg[]){
        Bridge b = new Bridge();
        for(int i = 0; i < 20; i++){
            (new Vehicle(Math.random()>0.5?true:false, b)).start();
        }
    }
}

 

Пример 2:

На схемата са нарисувани два моста с еднопосочно движение, като между тях има място, в което могат да се събират неограничен брой коли. Да се генерират случаен брой коли от ляво и отдясно, които трябва да преминат през двата моста. Всяка кола да изчаква известно, случайно определено време, преди да се опита да мине по някои от мостовете и да губи определено фиксирано време за преминаване по всеки от мостовете. За да може една кола да стъпи на даден мост, на него или трябва да има коли движещи се в същата посока, или да няма коли. Да се състави апликация на Java, която моделира ситуацията.