public class TestIt{
public static class QuizIt{
public static void doQuizStuff(){
//TestIt.ExtraQuizStuff(); //Line(2)
}
}
public void ExtraQuizStuff(){ //code for this method
}
}
public class MyClass{
public static void main(String[] args){
//(1)INSERT CODE HERE
}
}
Q1: What would have to be typed at line (1) in order to instantiate an instance of the nested class?
Q2: If we remove the "//" from the beginning of line 2, will the file still compile? Why or Why not?
Q1: What is meant by an "anonymous" inner class? Give your own coded example of an anonymous inner class.
Q2: Given the following code:
class Implement {
class Status{ }
}
class TestIt {
public static void main(String... args) {
Implement imp = new Implement();
//(1)INSERT CODE HERE
}
}
What would you have to type into line (1) above to create an instance of Status?
Q1: In the ButtonFrame.java file, identify the inner class. What does this inner class do in the file? Why did the programmer choose to make this class an inner class?
Compile both java files: ButtonFrame.java and ButtonTest.java then run ButtonTest to see the results.
Q1: Correct the following paragraph so that it tells the truth.
"Hello Susan, in response to your question yesterday, no, a method local inner class cannot be declared abstract, since you cannot subclass method local inner classes. You can declare method local inner classes to be final, but never static. If you declare them to be public, make sure that the outer class that contains the method is also declared public as well." Best regards, Brent...”
Q2: Given the following code:
public class TestIt {
public static void main(String[] args) {
public class Teacher {
public String name;
public Teacher(String s) {
name = s;
}
}
Object obj = new Teacher("Will I print? Hmmm...");
Teacher t = obj;
System.out.println(t.name);
}
}
Where is/are the error/s located, and describe the nature of the error/s?
Q1: Write a program that has the following features.
Creating a Thread and Putting It to Sleep
In this exercise we will create a simple counting thread. It will count to 100, pausing one second between each number. Also, in keeping with the counting theme, it will output a string every ten numbers.
Synchronizing a Block of Code
In this exercise we will attempt to synchronize a block of code. Within that block of code we will get the lock on an object, so that other threads cannot modify it while the block of code is executing. We will be creating three threads that will all attempt to manipulate the same object. Each thread will output a single letter 100 times, and then increment that letter by one. The object we will be using is StringBuffer. We could synchronize on a String object, but strings cannot be modified once they are created, so we would not be able to increment the letter without generating a new String object. The final output should have 100 As, 100 Bs, and 100 Cs all in unbroken lines.
Q1. Which methods will enable a waiting Thread to return to the Runnable state?
Q2. Given the following code:
class MyThread extends Thread {
public MyThread (String s) {
super(s);
}
public void run() {
System.out.println("Hello, I am "+ getName());
}
}
public class TestThread {
public static void main (String arg[]) {
MyThread t1, t2;
t1 = new MyThread ("Thread #1");
t2 = new MyThread ("Thread #2");
t2.start();
t1.start();
}
}
Write a program TestThreadMany.java that takes a positive integer n from the command line and creates exactly n threads that print out their own name. (You can do this using a Scanner object to obtain a value typed in from the command line, or you will need to convert the String arg[0] into an int (from previous lessons))
Q1: Which is the correct way to start a new thread? Select the one correct answer.
(a) Just create a new Thread object. The thread will start automatically.
(b) Create a new Thread object and call the method begin().
(c) Create a new Thread object and call the method start().
(d) Create a new Thread object and call the method run().
(e) Create a new Thread object and call the method resume().
Q2: When extending the Thread class to implement the code executed by a thread, which method should be overridden? Select the one correct answer.
(a) begin()
(b) start()
(c) run()
(d) resume()
(e) behavior()
Q3: Which statements are true? Select the two correct answers.
(a) The class Thread is abstract.
(b) The class Thread implements Runnable.
(c) The Runnable interface has a single method named start().
(d) Calling the method run() on an object implementing Runnable will create a new Thread.
(e) A program terminates when the last user thread finishes.
Q4: What will be the result of attempting to compile and run the following program?
public class MyClass extends Thread{
public MyClass(String s){ msg = s; }
String msg;
public void run(){
System.out.println(msg);
}
public static void main(String[] args){
new MyClass("Hello");
new MyClass("World");
}
}
Select the one correct answer.
(a) The program will fail to compile.
(b) The program will compile without errors ans will print Hello and World, in the standard output.
(c) The program will compile without errors and will print a never-ending stream of Hello and World.
(d) The program will compile without errors and will print Hello and World when run, but the order is unpredictable.
(e) The program will compile without errors and will simply terminate without any output when run.
Q5: What will be the result of attempting to compile and run the following program?
class Extender extends Thread{
public Extender(){}
public Extender(Runnable runnable){super(runnable);}
public void run(){ System.out.println("|Extender|");}
}
public class Implementer implements Runnable{
public void run(){ System.out.print("|Implementer|");}
public static void main(String[] args){
new Extender(new Implementer()).start();
new Extender().start();
new Thread(new Implementer()).start();
}
}
Select the one correct answer.
(a) The program will fail to compile.
(b) The program will compile without errors and will print |Extender| twice and |Implementer| once, in some order, every time the program is run.
(c) The program will compile without errors and will print |Extender| once and |Implementer| twice, in some order, every time the program is run.
(d) The program will compile without errors and will print |Extender| once and |Implementer| once, in some order, every time the program is run.
(e) The program will compile without errors and will simply terminate without any output when run.
(f) The program will compile without errors, and will print |Extender| once and |Implementer| once, in some order, and terminate because of a runtime error.
Q6: What will be the result of attempting to compile and run the following program?
class R1 implements Runnable{
public void run(){
System.out.print(Thread.currentThread().getName());
}
}
public class R2 implements Runnable{
public void run(){
new Thread(new R1(),"|R1a|").run();
new Thread(new R1(),"|R1b|").start();
System.out.print(Thread.currentThread().getName());
}
public static void main(String[] args){
new Thread(new R2(),"|R2|").start();
}
}
Select the once correct answer.
(a) The program will fail to compile.
(b) The program will compile without errors and will print |R1a| twice and |R2| once, in some order, every time the program is run.
(c) The program will compile without errors and will print |R1b| twice and |R2| once, in some order, every time the program is run.
(d) The program will compile without errors and will print |R1b| once and |R2| twice, in some order, every time the program is run.
(e) The program will compile without errors and will print |R1a| once, |R1b| once, and |R2| once, in some order, every time the program is run.
Q7: What will be the result of attempting to compile and run the following program?
public class Threader extends Thread{
Threader(String name){
super(name);
}
public void run() throws IllegalStateException{
System.out.println(Thread.currentThread().getName());
throw new IllegalStateException();
}
public static void main(String[] args){
new Threader("|T1|").start();
}
}
Select the one correct answer.
(a) The program will fail to compile.
(b) The program will compile without errors, will print |T1|, and will terminate normally every time the program is run.
(c) The program will compile without errors, and will print |T1|, and throw and IllegalStateException, every time the program is run.
(d) None of the above.
Q8: What will be the result of attempting to compile and run the following program?
public class Worker extends Thread{
public void run(){
System.out.print("|work|");
}
public static void main(String[] args){
Worker worker = new Worker();
worker.start();
worker.run();
worker.start();
}
}
(a) The program will fail to compile.
(b) The program will compile without errors, will print |work| twice, and terminate normally every time the program is run.
(c) The program will compile without errors, will print |work| thrice, and terminate normally every time the program is run.
(d) The program will compile without errors, will print |work| twice, and throw an IllegalStateException, every time the program is run.
(e) None of the above.
Q1: Given the following program, there is an error present in the code. Find the error then fix the error. Then select the two correct answers from the selection below the code.
public class ThreadPrint{
static Thread makeThread(final String id, boolean daemon){
Thread t = new Thread(id){
public void run(){
System.out.println(id);
}
}
t.setDaemon(daemon);
t.start();
return t;
}
public static void main(String[] args){
Thread a = makeThread("A",false);
Thread b = makeThread("B",true);
System.out.print("Endn");
}
}
Note: daemons will not be on the exam, but I chose this problem because it is still a good question concerning threads in general. You may have to reference the online documentation concerning the setDaemon method, and how daemons work at an elementary level. Since this course will be moving onto the SCJP 6.0 exam in the future, this is why I felt it important to include daemon's in this assignment.
Which are always true concerning this code?
(a) The letter A is always printed.
(b) The letter B is always printed.
(c) The letter A is never printed after End.
(d) The letter B is never printed after End.
(e) The program might print B, End, and A in that order.
Q2: Given the following program, which alternatives would make good choices to synchronize on at (1)?
public class Preference{
private int account1;
private Integer account2;
public void doIt(){
final Double account3 = new Double(10e10);
synchronized(/* (1)INSERT CODE HERE */){
System.out.print("doIt");
}
}
}
(a) Synchronized on account1
(b) Synchronized on account2
(c) Synchronized on account3
(c) Synchronized on this.
Q3: Which statements are not true about the synchronized block? (There may be more than one.)
(a) If the expression in a synchronized block evaluates to null, a
NullPointerException will be thrown.
(b) The lock is only released if the execution of the block terminates
normally.
(c) A thread cannot hold more than one lock at a time.
(d) Synchronized statements cannot be nested.
(e) The braces cannot be omitted even if there is only a single statement to execute in the block.
Q4: In the following email, Frohicky the extremely bad "java tech guy" wrote a response email to a java client. Unfortunately, only one thing that he said in the email was true. Find the true comment, and then explain why the other statements are false, then correct them.
from: frohicky@javahelp.net
to : ted_the_java_guy@yahhoy.com
"Dear ted,
In response to your previous question you need to make sure that you do not implement recursion since an object that is already locked will not allow new invocations of a synchronized method. You also must further understand that synchronized methods can only call other synchronized methods. In the Java language, no two threads can concurrently execute synchronized methods on the same object, and that inside of a synchronized method, one can assume that no other threads are currently executing any other methods of the same class.
Thank you for contacting your Java Help professionals.
Sincerely Frohicky..."
Q5: Given the following code:
public class MyClass extends Thread{
static Object lock1 = new Object();
static Object lock2 = new Object();
static volatile int i1, i2, j1, j2, k1, k2;
public void run() { while(true){ doIt(); check(); } }
void doIt(){
synchronized(lock1){ i1++; }
j1++;
synchronized(lock2){ k1++; k2++; }
j2++;
synchronized(lock1){ i2++; }
}
void check(){
if(i1 != i2) System.out.println("i");
if(j1 != j2) System.out.println("j");
if(k1 != k2) System.out.println("k");
}
public static void main(String[] args){
new MyClass().start();
new MyClass().start();
}
}
Why is this code dangerous to run? How can it be fixed? Are all print statements in the code reachable? If not, why not? Explain why j1 and j2 are sometimes not equal in this code.
Q6: Given the following program, which code modifications will result in both threads being able to participate in printing one smiley (:-)) per line continuously?
public class Smiley extends Thread{
public void run(){ //1
while(true){ //2
try{ //3
System.out.print(":"); //4
sleep(100); //5
System.out.print("-"); //6
sleep(100); //7
System.out.println(")"); //8
sleep(100); //9
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
new Smiley().start();
new Smiley().start();
}
}
Select the two correct answers.
(a) Synchronize the run() method with the key word synchronized //1
(b) Synchronize the while loop with a synchronized(Smiley.class) block //2
(c) Synchronize the try-catch construct with a synchronized(Smiley.class)
block. //3
(d) Synchronize statements //4 to //9 with one synchronized(Smiley.class) block.
(e) Synchronize each statement //4, //6, //8 individually with a synchronized (Smiley.class) block.
(f) None of the above will give the desired result.
Q1: A thread dies when what happens? How many times can a thread be started?
Q2: Which statement/s is/are true about the following code? There may be more than one answer.
public class Joining{
static Thread createThread(final int i, final Thread t1){
Thread t2 = new Thread(){
public void run(){
System.out.println(i+1);
try{
t1.join();
}catch(InterruptedException ie){ }
System.out.println(i+2);
}
};
System.out.println(i+3); //1
t2.start(); //2
System.out.println(i+4); //3
return t2;
}
public static void main(String[] args){
createThread(10, createThread(20, Thread.currentThread()));
}
}
(a) The first number printed is always 23.
(b) The number 14 is printed before the number 22.
(c) The number 24 is printed before the number 21.
(d) The last number printed is 12.
(e) The number 11 is printed before the number 23.
Using the same code above, after the start() method is invoked on t2, what is the next step the scheduler will do? Is this even predictable? What are the options that the scheduler can do after line //2?
Q3: Given the following code:
public class ThreadAPI{
private static Thread t1 = new Thread("T1"){
public void run(){
try{ wait(1000); } catch(InterruptedException ie){}
}};
private static Thread t2 = new Thread("T2"){
public void run(){
notify();
}};
private static Thread t3 = new Thread("T3"){
public void run(){
yield();
}};
private static Thread t4 = new Thread("T4"){
public void run(){
try{ sleep(100); } catch(InterruptedException ie){}
}};
public static void main(String[] args){
t1.start(); t2.start(); t3.start(); t4.start();
try{ t4.join(); } catch(InterruptedException ie){}
}
}
Explain what results the code will give. Will it compile? What kind of errors/ exceptions do you get? Where are they coming from and why?
Q4: Which code, when inserted at (1), will result in the program compiling and printing Done on the standard input stream, and then all threads terminating normally?
public class RunningThreads{
private static Thread t1 = new Thread("T1"){
public void run(){
synchronized(RuningThreads.class){
try{
//(1) INSERT CODE HERE...
}catch(InterruptedException ie){ ie.printStackTrace(); }
System.out.println("Done");
}}};
public static void main(String[] args){
t1.start();
try{
t1.join();
}catch(InterruptedException ie){ie.printStackTrace(); }
}
}
Select the correct answer/s (There may be more than one)
(a) wait();
(b) wait(100);
(c) RunningThreads.class.wait();
(d) RunningThreads.class.wait(100);
(e) yield();
(f) sleep(100);
Q5: What can be guaranteed by calling the method yield()?
Q6: In which class or interface is the notify() method defined?
Q7: How can the priority of a thread be set?
Q8: Which of the following statements are true about locks?
(a) A thread can hold more than one lock at a time.
(b) Invoking wait() on a Thread object will relinquish all locks held by the thread.
(c) Invoking wait() on an object whose lock is held by the current thread will relinquish the lock.
(d) Invoking notify() on an object whose lock is held by the current thread will relinquish the lock.
(e) Multiple threads can hold the same lock at the same time.
Q9: What will be the result of invoking the wait() method on an object without ensuring that the current thread holds the lock of the object?
Q10: Which of the following are plausible reasons why a thread might be alive, but still not be running? (There may be multiple answers.)
(a) The thread is waiting for some condition as a result of a wait() call.
(b) The execution has reached the end of the run() method.
(c) The thread is waiting to acquire the lock of an object in order to execute a certain method on that object.
(d) The thread does not have the highest priority and is currently not executing.
(e) The thread is sleeping as a result of a call to the sleep() method.
Q11: What will the following program print when compiled and run?
public class Tank{
private boolean isEmpty = true;
public synchronized void emptying(){
pause(true);
isEmpty = !isEmpty;
System.out.println("emptying");
notify();
}
public synchronized void filling(){
pause(false);
isEmpty = !isEmpty;
System.out.println("filling");
notify();
}
private void pause(boolean flag){
while(flag ? isEmpty : !isEmpty){
try{
wait();
}catch(InterruptedException ie){
System.out.println(Thread.currentThread() + " interrupted.");
}
}
}
public static void main(String[] args){
final Tank token = new Tank();
(new Thread("A"){public void run(){for(;;) token.emptying();}}).start();
(new Thread("B"){public void run(){for(;;) token.filling();}}).start();
}
}
Select the one correct answer:
(a) The program will compile and continue running once started, but will not print anything.
(b) The program will compile and continue running once started, printing only the string "emptying".
(c) The program will compile and continue running once started, printing only the string "filling".
(d) The program will compile and continue running once started, always printing the string "filling" followed by the string "emptying".
(e) The program will compile and continue running once started, printing the strings "filling" and "emptying" in some order.
Q12: What will the following program print when compiled and run?
public class Syncher2{
final static int[] intArray = new int[2];
private static void pause(){
while(intArray[0]==0){
try{ intArray.wait(); }
catch(InterruptedException ie){
System.out.println(Thread.currentThread() + " interrupted.");
}
}
}
public static void main(String[] args){
Thread runner = new Thread(){
public void run(){
synchronized(intArray){
pause();
System.out.println(intArray[0] + intArray[1]);
}}};
runner.start();
intArray[0] = intArray[1]=10;
synchronized(intArray){
intArray.notify();
}
}
}