java threads,

Ace your homework & exams now with Quizwiz!

When the class has been carefully synchronized to protect its data we say that the class is ______

thread safe e.g. StringBuffer is synchronized and therefore thread safe. It can therefore be used in a multithreaded environment

how can you start a thread but tell it not to run until some other thread has finished?

use the join() method

wait() method must be placed inside a ______ ______ and

wait() method must be placed inside a SYNCHRONIZED BLOCK and TRY block e.g. synchronized( this ) { try { b.wait(); } catch( Exception e) { } }

When a thread wakes up it goes back to the ______ state

when a thread wakes up it simply goes back to the Runnable state

List 2 ways to define and instantiate a thread

#1 *Extend* the *java.lang.Thread* class i.e. class A *extends Thread* {...} #2 *Implement* the *Runnable* interface i.e. class A *implement Runnable* {...}

List the thread states

#1 New #2 Runnable #3 Running #4 waiting/blocked/sleeping #5 dead

List four methods of the Thread class

*S-Y-S-R* *start()* *yield()* *sleep()* *run()*

Complete the following to enable the thread to sleep for 1000 ms: class A implements Runnable { public void run() { System. out. println( "Run + Thread. currentThread(). getName()); _________ } public static void main(String[] args) { A a = new A(); Thread t = new Thread(a); t.start(); } }

.... public void run() { System. out. println( "Run + Thread. currentThread(). getName()); try { Thread. sleep(1000); } catch( InterruptedException ex) { } } ...sleep() must be in try catch block

What's a deadlock ?

A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.

public class A implements Runnable { public void run() { System. out. println( "A Run"); } public static void main( String[] args) { A a = new A(); Thread t = new Thread(a); t.start(); t.start(); } } The above code will give: a) compiler error b) runtime error c) compile and print "A Run" twice d) none of the above

A is correct. Once a thread is started it can NEVER be started again. ----> If you call start() method a second time on a thread that already completed it's run() method ----> it will give Illegal Thread StateException which is like RuntimeException

class B { private int i = 2; public static synchronized void mA(){ System. out. println(i); } } The above code will give: a) compiler error b) runtime error c) compile and print 2 d) none of the above

A is correct. You cannot access a non static instance variable via a static method. Reason: how does a static method know which one of the millions upon millions of objects the nonstatic instance variable is belonged to? not possible therefore compiler error.

What is the difference between processes and threads ?

A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process.

Q: What difference you see between Process and Thread in Java?

A single process can own multiple threads. Thread are the smaller execution units of a Process. Processes possess their individual copy of the data segment of the parent process while the threads share the data portion of its process. Processes have their respective addresses while the Threads share the address space of the process. Processes can easily communicate with child processes using IPC (interprocess communication). While, the threads communicate with other threads of the same process using the wait(), notify(), notifyAll() methods.

How do you ensure that N threads can access N resources without deadlock ?

A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise.

When a thread's run() method has completed the above code: a) can re run on calling its start() method b) it will give exception if re-started c) none of the above

B is correct. Once a thread is started it can NEVER be started again. ----> If you call start() method a second time on a thread that already completed it's run() method ----> it will give Illegal Thread StateException which is like RuntimeException

Why is it not good object orientated practice to extend the Thread class?

Because *SUBCLASSING* should be reserved for *SPECIALIZING VERSIONS* of more *GENERAL SUPERCLASSES*.

how can you set threads priority directly?

By calling the setPriority() method e.g. A a = new A(); Thread t = new Thread(t); t.setPriority(8); t.start(); Priorities are set using a positive integer usually between 1 and 10. However values through 1 and 10 not guaranteed as the JVM might not recognize this.

which of the following can be synchronized: a) instance variables b) local variables c) methods d) code blocks

C and D are correct.

NEXT class A implements Runnable { public void run() { System. out. println( "A Run"); } public static void main(String[] args) { A a = new A(); Thread t = new Thread(a); t.start(); } } The above code will give: a) compiler error b) runtime error c) compile and print "A Run" d) none of the above

C is correct. You must use: A a = new A(); Thread t = new Thread(a); t.start(); in order to run the thread

how to extend the thread class?

Inherit from the Thread class, override its run() method, and write the functionality of the thread in the run() method.Then you create a new object of your class and call it's start method to run the thread.

When two threads are blocked this causes ______

DEADLOCK . This occurs when two threads are blocked with each WAITING for the others LOCK. Neither can run until the other gives up its a block so they sit there forever.

Explain the available thread states in a high-level.

During its execution, a thread can reside in one of the following states: NEW: The thread becomes ready to run, but does not necessarily start running immediately. RUNNABLE: The Java Virtual Machine (JVM) is actively executing the thread's code. BLOCKED: The thread is in a blocked state while waiting for a monitor lock. WAITING: The thread waits for another thread to perform a particular action. TIMED_WAITING: The thread waits for another thread to perform a particular action up to a specified waiting time. TERMINATED: The thread has finished its execution.

What is the difference between a synchronized method and a synchronized block ?

In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock).

what type of threads are used in the java language?

Java is a multi-threaded programming language. This means that our program can make optimal use of available resources by running two or more components concurrently, with each component handling a different task.

Q: What is the significance of using the <volatile> keyword?

Java permits threads to retrieve shared variables. If you declare a field as volatile, the Java memory model ensures that all threads see a consistent value of the variable.

what does the loader class do with threads?

Loader class extends the Thread class and overrides its run() method. When we create the obj object and call its start() method, the run() method statements execute on a different thread.

Name the thread state: This is the state the thread is in after the Thread instance has been created but the start() method has not been invoked under thread

New State

Q: Does Java support the <volatile> methods?

No, <volatile> is a standard keyword which you can only use for variables.

Q: Does Java enables support of synchronized variable?

No, synchronized keyword can be used only with methods, i.e. in the method declaration.

Q: Is it permissible to restart a Thread?

No, you can't start a Thread again. If you do so, the system will throw the runtimeException <java.lang.IllegalThreadStateException>. It occurs because the thread goes into the absolute state after executing the run() method.

Once a thread is started it can ________ be started again.

Once a thread is started it can NEVER be started again.

When multiple threads can access the same resource e.g. object instance variables and this may cause a ______ .

RACE CONDITION. This can produce corrupted data if one thread races in too quickly before an operation from the other thread has completed.

Name the thread state: This is the state in thread is in when it's eligible to run but the scheduler has not selected it to be the running thread

Runnable state

Name the thread state: This is the thread state a thread is in when the thread scheduler selects it from the runnable pool to be the currently executing process

Running state

Q: What is the process of Synchronization and why is it used?

Synchronization is a way of managing the access of shared resources in such a manner that not more than one thread could lock a particular resource at a given time. It is helpful in protecting your application resources when multiple threads are accessing them and may change their state that could lead to data corruption. Java supports it using the <synchronized> construct.

How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ?

The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock.

Which thread would you prefer and why ?

The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.

The _________ method causes the currently executing thread object to temporarily pause and allow other threads to execute

The java.lang.Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute

The order and duration of Threads run is controlled by the ________

The order and duration of Threads run is controlled by the SCHEDULER

how to create a runnable interface?

The other way of creating Threads is implementing the Runnable interface. Implement the run() method. Then, create a new Thread object, pass the Runnable class to its constructor, and start the Thread by calling the start() method.

The purpose of the yield() method is supposed to make the current running thread head back to runnable to allow other threads of the ______ ______ get their turn

The purpose of the yield() method is supposed to make the current running thread head back to runnable to allow other threads of the same priority get their turn in the running state

The ______ method is a static method of class Thread. You use it in your cord to slow a thread down

The sleep() method is a static method of class Thread. You use it in your cord to slow a thread down. You might think the thread is moving too quickly through its code.

Q: How do you define a Thread in Java?

The thread is the smallest unit of execution in a program. It consumes the CPU in an optimal manner and improves the performance of the application.

Explain different ways of creating a thread.

There are three ways that can be used in order for a Thread to be created: A class may extend the Thread class. A class may implement the Runnable interface. An application can use the Executor framework, in order to create a thread pool.

Q: Whar are the different ways to create Threads in Java?

There are two ways to create Threads i.e. by implementing the <java.lang.Runnable> interface or by extending the <java.lang.Thread> class and then defining the run method. e.g. Implement a thread by extending the Java thread class.Java public class ImplementThreadByExtend extends Thread{ public void run(){ // Write your code here. // Your code will get run by a new thread. } public static void main(String [] args){ ImplementThreadByExtend th = new ImplementThreadByExtend(); th.start(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 public class ImplementThreadByExtend extends Thread{ public void run(){ // Write your code here. // Your code will get run by a new thread. } public static void main(String [] args){ ImplementThreadByExtend th = new ImplementThreadByExtend(); th.start(); } } Implementing a thread using the Java Runnable interface.Java public class ImplementThreadByRunnable implements Runnable{ public void run(){ //... } public static void main(String [] args){ ImplementThreadByRunnable th = new ImplementThreadByRunnable(); Thread thread = new Thread(th); thread.start(); } } 1 2 3 4 5 6 7 8 9 10 11 12 public class ImplementThreadByRunnable implements Runnable{ public void run(){ //... } public static void main(String [] args){ ImplementThreadByRunnable th = new ImplementThreadByRunnable(); Thread thread = new Thread(th); thread.start(); } }

some characteristics of thread are

These are lightweight Java process. The thread class is a part of the <java.lang> package. You can create many threads in java, even the <main> method runs on a thread. Java supports the concurrent execution of multiple threads. Threads manage their stack

Q: What do you make of the daemon threads?

These are low priority threads that run intermittently in the background for the purpose of garbage collection.

name the three constants that can define a thread priority.

Thread.MIN_PRIORITY ----> priority 1 Thread.NORM_PRIORITY ----> priority 5 Thread.MAX_PRIORITY ----> priority 10

Name 3 Thread constants which defined the reign of thread priorities

Thread.Min_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10)

What method is supposed to make the currently running thread head back to Runnable to allow other threads of the same priority to get their turn.

Thread.yield() ----> this method isn't guaranteed to work because the JVM decides overall priority. yield() wont ever cause a thread to go to the waiting/sleeping/blocking state. it is supposed to make currently running thread head back to runnable.

Name the thread state: This is the state a thread is in when it's not eligible to run.

Waiting/block/sleeping state

which of the following are true: a) each object has just one lock b) each object can have more than one lock

a is correct.

Q: How would you difference between a thread starting with run() and start() method?

While using the start() method, the main thread internally invokes the run() method to launch newly created Thread. When you invoke the run() method, the main thread starts the run() method by itself.

how do you set thread priority?

You can set the thread priority with the setPriority() method.

class A implements Runnable { public void run() { System.out.println("A Run"); } public static void main(String[] args) { A a = new A(); a.start(); } } The above code will give: a) compiler error b) runtime error c) compile and print "A Run" d) none of the above

a is correct. class A *implements Runnable* { public void *run(){* *System.out.println("A Run"); }* public static void main(String[] args) { A a = new A(); a.*start()*; } } *Compiler error*: cannot find symbol A a = new A(); a.*start()*; Solution: *Create* a *thread* and *pass* the *object* a into it *then call start()* method i.e. public static void main(String[] args) { A *a* = new A(); *Thread t = new Thread(a);* t.*start()*; }

class A implements Runnable { public void run() { System. out. println( "Run + Thread. CurrentThread(). getName()); Thread. sleep(1000); } public static void main(String[] args) { A a = new A(); Thread t = new Thread(a); t.start(); } } The above code will: a) Compiler error b) Runtime error c) will Compile and run fine d) None of these

a is correct. sleep() must be wrapped in try/catch block ---> try { Thread. sleep(1000); } catch( InterruptedException ex) { }

class A { public static void main(String[] args) { B b = new B(); b.start(); synchronized(b) { System. out. println("waiting for b to complete"); b.wait(); } } } The above code will give: a) compiler error b) runtime error c) compile and print "waiting for b to complete" d) none of the above

a is correct. wait() method must be placed inside a SYNCHRONIZED BLOCK and TRY block e.g. synchronized( this ) { try { b.wait(); } catch( Exception e) { } }

a thread is considered dead when it is ______ method completes

a thread is considered dead when it is run() method completes

a thread is done being a thread when its target ________ method completes

a thread is done being a thread when its target run() method completes

class A { public static void main( String[] args) { B b = new B(); b.start(); synchronized(b) {try { System. out. println("waiting for b to complete"); b.wait(); } catch(Exception e) { } } } } The above code will give: a) compiler error b) runtime error c) compile and print "waiting for b to complete" d) none of the above

c is correct Note: wait() method must be placed inside a SYNCHRONIZED BLOCK and TRY block e.g. synchronized( this ) { try { b.wait(); } catch( Exception e) { } }

class A extends Thread { public void run(){ System.out.println("A Run"); } public static void main( String[] args) { A a = new A(); a.start(); } } The above code will give: a) compiler error b) runtime error c) compile and print "A Run" d) none of the above

c is correct. class A *extends Thread* { public void *run(){* *System.out.println("A Run");* *}* public static void main( String[] args) { A a = new A(); a.*start();* } } It prints "*A Run*". Note: we have *started* the *thread* as we have *called* the method *start()* which *IMPLICITLY* calls the *run()* method

class A extends Thread { public void run(){ System.out.println( "A Run"); } public static void main( String[] args) { A a = new A(); a.run(); } } The above code will give: a) compiler error b) runtime error c) compile and print "A Run" d) none of the above

c is correct. class A extends Thread { public void *run(){* *System.out.println( "A Run");* *}* public static void main( String[] args) { A *a* = new A(); *a.run()*; } } It prints "*A Run*". Note: we haven't started the thread as we haven't called the method start()

Which of the below will cause a compiler error: a ) public synchronized static void method(){ } b) public static synchronized void method(){ } c) public static void synchronized method(){ }

c is correct. A and B will compile and run fine.

class B { private static int i = 2; public static synchronized void mA(){ System. out. println(i); } } The above code will give: a) compiler error b) runtime error c) compile and print 2 d) none of the above

c is correct. Access to static fields should be done using static synchronized methods. Access to nonstatic fields or instance variables should be done via nonstatic methods.

import java. util.*; public class A { private List n = Collections. synchronizedList( new LinkedList()); public void mA() { n.size(); n.remove(0);} } The above code will give: a) compiler error b) runtime error c) is thread safe d) none of the above

d is correct. Even though Collections. synchronizedList(...) which enabled the collection to be thread safe ---- a thread can be executed in between size(); and n.remove(0); thus corrupting the data and not making the class thread safe Solution: synchronize the method public synchronized void mA() { n.size(); n.remove(0);} } therefore threads can only access this method one at a time

if a thread goes to sleep it releases any locks it has. True or false

false. It HOLDS any locks it has-it doesn't release them.

What is the name of the method to get a threads ID

getID()

A thread in Java begins as an instance of which class?

java.lang.*Thread*

does thread.sleep() throw exception?

keep in mind that Thread.sleep() throws an InterruptedException, so be sure to surround it with a try/catch block.

a thread gets a default priority that is the same as which method?

main() method. e.g. public static void main(String[] args) { MyThread t = new MyThread(); } ----> t thread has the same priority as the main thread

how can we solve the race condition on a method

make the method synchronized e.g. public synchronized void m() { ....} ----> only one thread can access this method at a time

explain the join() method

nonstatic join() is used where you have a thread B that can't do its work until another thread A has completed its work ----> you want to thread B to "join" thread a

not all ______ in a class need to be synchronized

not all METHODS in a class need to be synchronized

Explain yield() method

not guaranteed to do much of anything- although typically-it will cause the currently running thread to move back to runnable

Change the code below to only synchronize the return: public Myclass { public synchronized static int m(){ return i; } }

public Myclass { public static int m(){ synchronized (MyClass.class) { return i; } } } ----> MyClass.class is a class literal which is a special feature in the Java language to tell the compiler go and find me the instance of class that represents the class called MyClass

Change the code to synchronize the line: System. out. println("H"); in the method: public void method() { System. out. println("H"); }

public void method() { synchronized(this) { System. out. println("H"); } }

class A implements Runnable { public void run() { System. out. println( "Run " + Thread. ______ (). ______ ()); } public static void main( String[] args) { A a = new A(); Thread t = new Thread( a); t.start(); } } Complete the above code in order to get the name of the current thread

public void run() { System. out. println( "Run " + Thread. currentThread(). getName()); } ----> Thread. currentThread() returns a reference to the currently executing thread and then we invoke getName() ----> Output: Run Thread-0 ----> Default Name of thread a.

name the method that can set a threads priority directly

setpriority() e.g. FRunnable r = new FRunnable(); Thread t = new Thread(r); t.setpriority(8); t.start(); ---->priorities are set using a positive integer usually between 1 and 10. However values 1 through 10 are not guaranteed

if you have a thread B that can't do its work until another thread A has completed its work then you want thread b to ______

thread B to JOIN thread A

explain atomic operation

where two or more methods which fulfill a goal and never split up i.e. the two or more methods need to be performed as ONE ATOMIC operation and no other threads can execute in between these operations otherwise data will be corrupted

can static methods be synchronized?

yes


Related study sets

Developed/developing countries - Characteristics

View Set

Employee Training and Development Exam #2 Study Guide

View Set

APES Topic 1.8: Primary Productivity

View Set

Function and Structure of Proteins

View Set