public class CS313Thread {
private static class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());
System.out.println(Thread.currentThread().getState().name());
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread("Thread-1");
myThread.start();
}
}
public class MyCounter
{
private int i;
public MyCounter()
{
i = 0;
}
public void inc()
{
i = i + 1;
}
public void dec()
{
i = i - 1;
}
}
The class Driver declares one MyObject object and two threads, one of type ThreadA and one of type ThreadB. The ThreadA objects run() method calls the MyObjects method foo_a(), and the ThreadB objects run() method calls the MyObjects method foo_b(). The MyObject class is partly implemented, but its methods foo_a() and foo_b() are missing.
The output that the program could produce depends on these methods. Each question below has different versions of these methods. For each question, give all the possible outputs that the program could produce during different executions, if the versions of the methods in that question were included in the MyObject class (see location in comments). If any output can be produced in more than one way, write it only once.
Note that a call to MyObject's print() method prints the values of both MyObject fields var1 and var2. Any output which would be produced during one execution would appear on the same output line. Dont miss the call to myObject.print() at the end of the Driver class main() method.
public class MyObject {
private int var1 = 1, var2 = 2;
// foo_a() and foo_b() SHOULD APPEAR HERE!!!
public synchronized void print() {
System.out.print("" + var1 + " " + var2 + " ");
}
}
public class Driver {
public static void main(String args[]) {
MyObject myObject = new MyObject();
ThreadA ta = new ThreadA(myObject);
ThreadB tb = new ThreadB(myObject);
ta.start();
tb.start();
myObject.print();
}
}
public class ThreadA extends Thread {
private MyObject my_object;
public ThreadA(MyObject m) {
my_object = m;
}
public void run() {
my_object.foo_a();
}
}
public class ThreadB extends Thread {
private MyObject my_object;
public ThreadB(MyObject m) {
my_object = m;
}
public void run() {
my_object.foo_b();
}
}
public void foo_a() {
var1 = var2;
}
public void foo_b() {
var2 = var1;
}
public synchronized void foo_a() {
var1 = var2;
}
public synchronized void foo_b() {
var2 = var1;
}
public synchronized void foo_a() {
var1 = 3;
}
public synchronized void foo_b() {
var2 = 4;
}
public synchronized void foo_a() {
var1 = 3;
}
public void foo_b() {
var2 = 4;
}
1a thread1() {
2a synchronized(m) {
...
3a }
...
4a synchronized(m) {
...
5a }
...
6a synchronized(m) {
...
7a }
...
8a }
1b thread2() {
2b synchronized(m) {
...
3b }
...
4b synchronized(m) {
...
5b }
...
6b synchronized(m) {
...
7b }
...
8b }