// Code of Quiz 6.3 // Filename: Quiz6_3 class Foo{ private int content; private String name; public Foo(String s){ content = 0; name = s; } public synchronized void addContent(int k) { content = content + k; } public synchronized void printContent() { System.out.print(content+" "); } public synchronized void printName() { System.out.print(name+" "); } } class MyThread extends Thread{ private Foo f; public MyThread(Foo f){ this.f = f; } public void run(){ try {sleep((long)(java.lang.Math.random()*6));} catch(InterruptedException e) { return; }; f.printName(); //Print the name of f try {sleep((long)(java.lang.Math.random()*6));} catch(InterruptedException e) { return; }; f.addContent(1); //Update the content of f try {sleep((long)(java.lang.Math.random()*6));} catch(InterruptedException e) { return; }; f.printContent(); //Print the content of f } } public class Quiz6_3{ public static void main(String[] args) { Foo f = new Foo("Giorgio"); MyThread T1 = new MyThread(f); MyThread T2 = new MyThread(f); T1.start(); T2.start(); } }