Given the main method below and its output: public class TwoThreadsDemo { public
ID: 3767828 • Letter: G
Question
Given the main method below and its output:
public class TwoThreadsDemo {
public static void main (String[] args) {
new SimpleThread("CECS 277").start();
new SimpleThread("OOP in Java").start();
}
}
Output
0 OOP in Java
0 CECS 277
1 OOP in Java
2 OOP in Java
1 CECS 277
3 OOP in Java
4 OOP in Java
2 CECS 277
5 OOP in Java
3 CECS 277
4 CECS 277
5 CECS 277
6 OOP in Java
6 CECS 277
7 OOP in Java
7 CECS 277
8 CECS 277
8 OOP in Java
9 CECS 277
DONE! CECS 277
9 OOP in Java
DONE! OOP in Java
Implement the class SimpleThread.
Explanation / Answer
Solution:
package com.chegg.nancy.solutions;
class SimpleThread extends Thread {
private Thread t;
private String threadName;
int i = 0;
SimpleThread(String name) {
threadName = name;
System.out.println(i++ + " " + threadName);
}
public void run() {
System.out.println(i++ + " " + threadName);
try {
while (i <= 9) {
System.out.println(i++ + " " + threadName);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("DONE!" + threadName);
}
public void start() {
System.out.println(i++ + " " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}
public class TwoThreadsDemo {
public static void main(String[] args) {
new SimpleThread("CECS 277").start();
new SimpleThread("OOP in Java").start();
}
}
Important: One can not imagine the order of threds execution.That is totally unpredictable.
Output:
0 CECS 277
1 CECS 277
0 OOP in Java
1 OOP in Java
2 CECS 277
3 CECS 277
2 OOP in Java
3 OOP in Java
4 CECS 277
4 OOP in Java
5 CECS 277
5 OOP in Java
6 CECS 277
6 OOP in Java
7 CECS 277
7 OOP in Java
8 CECS 277
8 OOP in Java
9 CECS 277
9 OOP in Java
DONE!CECS 277
DONE!OOP in Java
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.