















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
















































// main terminates, but in Java the other threads keep running // and hence Java program continues running
class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; }
public void run() { for (;;) { System.out.println(name + ": hello world"); } } }
public class Main2 {
public static void main(String [] args) { MyThread t1 = new MyThread("thread1"); MyThread t2 = new MyThread("thread2"); t1.start(); t2.start(); }
}
class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; }
public void run() { for (;;) { System.out.println(name + ": hello world"); yield(); } } }
public class Main3 {
public static void main(String [] args) { MyThread t1 = new MyThread("thread1"); MyThread t2 = new MyThread("thread2"); t1.start(); t2.start(); }
}
// on my system: 1; Mac OS X 2/21/
class SharedData { public int a = 0; public String s = null;
public SharedData() { a = 10; s = "Test"; } }
class MyThread extends Thread { private SharedData m_data = null;
public MyThread(SharedData data) { m_data = data; }
public void run() { for (;;) { m_data.a++; } } }
public class Main5 {
public static void main(String [] args) { SharedData data = new SharedData(); MyThread t1 = new MyThread(data); t1.start();
for (;;) { data.a--; } }
}
If we have multiple threads accessing this
shared data, how do we synchronize access to
ensure it remains in a consistent state?