Lab11 - Interfaces - Inner Classes - Threading
Lab11 - Interfaces - Inner Classes - Threading
Lab 11
Content
• Interfaces
– What are interfaces
– Ordered
– Derived
– Comparable
• Inner classes
– Static Inner Classes
– Public Inner Classes
– Nested Inner Classes
– Inheriting Inner Classes
– Anonymous Classes
• Threads and Multithreading
– Threads in Java
– Thread Lifecycle
– Synchronization
– Thread Priorities
2
Interfaces
• What is an Interface?
– An interface is a collection of “abstract” methods.
– An interface is a template that a class must adhere to.
– A class implements an interface, thereby inheriting the abstract methods
of the interface.
• Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
3
Interfaces
• An interface is similar to a class in the following ways:
– An interface can contain any number of methods.
– An interface is written in a file with a .java extension, with the name of
the interface matching the name of the file.
– The byte code of an interface appears in a .class file.
4
Interfaces
• An interface is different from a class in several ways:
– You cannot instantiate an interface.
– An interface does not contain any constructors.
– All of the methods in an interface are abstract.
– An interface cannot contain instance variables. The only fields that can
appear in an interface must be declared both static and final.
– An interface is not extended by a class; it is implemented by a class.
– An interface can extend multiple interfaces.
5
Interfaces
• An interface and all of its method headings should be declared public
– They cannot be given private, protected, or package access
• When a class implements an interface, it must make all the methods in the
interface public
6
Interfaces
• How do I define an Interface…
□ Keyword interface
public interface InterfaceName{
□ Methods are not defined.
public returnType method1(); Note you do not use the
public returnType method2(); keyword abstract
□ The interface is implem
public returnType method3(); ented by a class
}
7
The Ordered Interface
8
Interfaces
• To implement an interface, a concrete class must do two things:
1. It must include the phrase implements Interface_Name at the start of the
class definition
• If more than one interface is implemented, each is listed, separated by commas
2. The class must implement all the method headings listed in the definition(s) of the
interface(s)
9
The Ordered Interface
10
Interfaces
• An abstract class may implement an interface, However:
1. It is not imperative that all methods be implemented.
2. Unimplemented methods must be marked as abstract;
11
Derived Interfaces
• Like classes, an interface may be derived from a base
interface
– This is called extending the interface
– The derived interface must include the phrase
• extends BaseInterfaceName
• A concrete class that implements a derived interface
must have definitions for any methods in the derived
interface as well as any methods in the base interface
12
Derived Interfaces
13
Comparable interface
• Can be used to provide a single sorting method.
14
Comparable interface
• int compareTo(Object other);
Must return
– A negative number if the calling object "comes before" the parameter
other
– A zero if the calling object "equals" the parameter other
– A positive number if the calling object "comes after" the parameter
other
• If the parameter other is not of the same type as the class being defined,
then a ClassCastException should be thrown
15
Writing Comparable
• The following shows an example of the compareTo method
16
Using Comparable
• Sort
17
Comparable interface
18
Comparable interface
19
Comparable interface
20
Constants in Interfaces
• Java allows for defining constants in interface
21
Inconsistencies in Interfaces
• Two form of inconsistencies may arise with interfaces
– Inconsistent constants
– Inconsistent methods
22
Self-Test
• 프로젝트 명: Project11_1
– git commit –m “Project11_1”
23
Self-Test
• 프로그램이 정상적으로 동작한다면 아래의 결과가 Console에 표시된다.
Move Type : 0
Attack : false
ItemList : 5
----------------------------------
Move Type : 2
Attack : true
ItemList
Item[0] : HP (50)
Item[1] : MP (30)
Item[2] : Food (100)
Item[3] : Key (10)
Item[4] : Gold (1)
----------------------------------
ItemList
Item[0] : Gold (1)
Item[1] : Key (10)
Item[2] : MP (30)
Item[3] : HP (50)
Item[4] : Food (100)
----------------------------------
24
Inner Classes
• Inner Classes are classes defined within other classes
• The class that includes the inner class is called the outer class
25
Class with an Inner Class
26
Class with an Inner Class
27
Class with an Inner Class
28
Inner Class
Output
0
2
4
6
8
10
12
14
29
Static Inner Classes
• A normal inner class has a connection between its objects and
the outer class object that created the inner class object
– This allows an inner class definition to reference an instance variable, or
invoke a method of the outer class
• There are certain situations, however, when an inner class
must be static
– If an object of the inner class is created within a static method of the
outer class. {Builder design pattern}
– If the inner class must have static members
30
Public Inner Classes
• If an inner class is marked public, then it can be used outside of
the outer class
– Create an object using an instance of the outer class {non-static}
– Use the Outer class’ name to access the inner class {static}
31
Nested Inner Classes
• It is possible to nest an inner class within another inner class
• This however makes the notation for accessing the nested inner class
longer.
32
Inheriting Inner Classes
• It is possible to inherit an outer class that has an inner class
33
Anonymous Classes
• If an object is to be created, but there is no need to name the
object's class, then an anonymous class definition can be used
– The class definition is embedded inside the expression with the new
operator
34
Anonymous Classes
35
Anonymous Classes
36
Anonymous Classes
37
Threads & Multithreading
• A thread is a separate computation process.
– Threads can be thought of as computations that execute in parallel.
– A thread is a single sequential flow of control within a program.
– Thread does not have its own address space but uses the memory and other
resources of the process in which it executes.
– There may be several threads in one process
• Characteristics of threads
– Threads are lightweight processes as the overhead of switching between
threads is less
38
Threads & Multithreading
• We have experienced threads
• The Java Virtual Machine spawns a thread when your program is run called the Main Thread
39
Threads & Multithreading
• Multithreading is a programming concept where a program
(process) is divided into two or more subprograms (process),
which can be implemented at the same time in parallel
• Why do we need threads?
– To enhance parallel processing
– To increase response to the user
– To utilize the idle time of the CPU
– Prioritize your work depending on priority
• E.g.
– Video Games
– Web Server
• The web server listens for request and serves it
40
Threads & Multithreading
41
Threads in Java
• Java contains a Thread class and a Runnable interface.
– There are 2 ways we can use threads
• extending the class Thread.
public class MyThreadClass extends Thread{.. }
• Implementing Runnable interface.
public class MyThreadClass implements Runnable{.. }
Note: It is usually more preferred to implement the Runnable Interface so that we can extend
properties from other classes
42
Thread Lifecycle
When threads are created they may go The states of threads may be controlled
through the following states. by these methods.
New (Newborn) start()
Runnable yield()
Running suspend(), sleep(), wait()
Blocked resume(), notify()
Terminated (Dead) stop()
43
Thread Lifecycle
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a simple method call.
• Creating an object does not create a thread, calling start() method creates the
thread.
44
Producer Consumer
• Let us examine a simple producer consumer example
• In this example
– We have a producer thread that creates a random number.
– We also have a consumer thread that consumes the random number.
45
Producer Consumer
• The main method of the producer consumer creates two threads.
– One producer thread
– One consumer thread
Something’s fishy
with our results…
46
Synchronization
• Multithreading introduces an asynchronous behavior to your programs.
• We must force synchronicity if needed.
• This is done by using the keyword synchronized
47
Synchronization
• How it works.
• When a thread begins to execute a synchronized method it automatically acquires
a lock on that object.
• The lock is relinquished when the method ends.
• Only one thread can have the lock at a particular time
• Therefore only one thread can execute the synchronized instance method of the
same object at a particular time.
48
Synchronized Producer Consumer
• This version of the producer consumer has a single stacked buffer
• The producer adds data to the buffer and waits if it is full
• The consumer takes data from the buffer and waits if empty
49
Synchronized Producer Consumer
• How the program works
50
Synchronized Producer Consumer
51
Synchronized Producer Consumer
52
Synchronized Producer Consumer
53
Other Methods
Method Meaning
Thread currentThread() returns a reference to the current thread
Void sleep(long msec) causes the current thread to wait for msec milliseconds
54
Thread Priorities
• In java, each thread is assigned a priority, which affects the order in which it
is scheduled for running.
• Java permits us to set the priority of a thread using the setPriority() method
as follows:
ThreadName.setPriority(intNumber);
• The intNumber may assume one of these constants or any value between 1
and 10.
• The intNumber is an integer value to which the thread’s priority is set. The
Thread class defines several priority constants:
– MIN_PRIORITY : 1
– NORM_PRIORITY : 5
– MAX_PRIORITY : 10
55
Self-Test (2)
• 프로젝트 명: Project11_2
– git commit –m “Project11_2”
– 당일 밤 12시까지 제출
56
Self-Test (2)
• 아래처럼 Console 창에 출력되는지 확인한다.
(출력되는 모양은 정확하게 일치하지 않을 수 있다.)
57