Wk2L1 - Intro to Threads & Processes 2 Flashcards
What is the Runnable Interface in Java?
The Runnable interface in Java contains only one abstract method, run(), which must be implemented to define the thread’s behavior. Unlike extending the Thread class, implementing Runnable allows multiple interfaces to be used.
What is the difference between extending the Thread class and implementing Runnable?
Extending Thread: Allows overloading of methods other than run(), but a class can only inherit from one class.
Implementing Runnable: Only requires the implementation of run(). Memory may be shared between threads depending on the objects passed.
What does the Thread.join() method do?
The join() method makes the main thread wait until the spawned threads finish their execution. It is useful when you need to ensure all threads have completed before moving on to the next task.
When would you use the join() method in a multithreaded program?
You would use join() when a task requires other threads to finish before continuing execution, ensuring that the program does not move forward until all threads are done.
What are the benefits of using the Runnable Interface?
Implementing Runnable provides more flexibility by allowing the class to implement multiple interfaces, and you can control whether memory is shared between threads by passing the same or different objects to them.
What are association and inheritance in Object-Oriented Programming (OOP)?
Association: Represents a “has a” relationship between objects.
Inheritance: Represents an “is a” relationship, where a subclass inherits methods and properties from a superclass.
What is an abstract class in Java?
An abstract class contains abstract methods with no implementation and is too generalized to be used for creating objects directly. It serves as a blueprint for subclasses.
How does memory sharing work with threads in Java?
Memory can be shared between threads when the same object is passed to each thread. However, if different objects are passed, the threads will not share memory.
What is the difference between Inheritance and Interface in Java?
Inheritance:
- Represents an “is a” relationship.
- A subclass inherits properties and methods from a single superclass.
- A class can only inherit from one superclass.
- Allows overriding methods from the parent class.
- Example: A Dog class extends an Animal class because a dog “is an” animal.
Interface:
- Represents a “can do” relationship.
- A class can implement multiple interfaces.
- Contains only abstract methods that must be implemented.
- Provides a blueprint for behavior that can be shared across classes without using inheritance.
- Example: A Dog class implements a Runnable interface because a dog “can run.”