notes

advertisement

cs203 / Prof, Miller Amir Chartab Shargh 04-02-07

First of all I want say t h anks to Prof. Jmiller for giving us the opportunity to access the previous

203 course materials and allow us to use it.

NOTES

"Notes" is posted on the web page as Notes http://www.calstatela.edu/faculty/jmiller6/cs203-spring2007/notes.html

2 days to submit "Notes"

Submit:

1) Word document of typed notes [notes.doc]

2) Any source code written in class

REVIEW

In 202 we learned:

1) OOP - Object Oriented Programming

2) Inheritance:

Interfaces

Classes

3) Keywords

4) GUI - Graphical User Interface

5) Exception Handling

Keywords : Any word used in Java that is naturally a part of the programming language. All

Keywords in Java are lower-case. CLASS NAMES ARE NOT Keywords.

Examples of Keywords: for, while, if, else, do, switch, try, catch, class, public, static, void

Question: What makes a language object oriented?

Answer: The fact that we can create/use objects.

Objects are structures that contain data, and a set of operations to be performed on the data.

Unlike C++, everything is in a class in Java. In order to use a class we must 1) create it

2) Instantiate it

In Java, as well as in C++, we instantiate a class using the keyword "new".

Eg.

Consider the class, C1. We instantiate it by:

C1 c = new C1( );

Here, 'c' becomes an instance of C1. Luckily, we don't have to deal with pointers in Java.

However, all objects in Java are passed by Reference , therefore making all objects in Java to be pointers.

Pass by Value

All primitive data types:

1) boolean 2) byte 3) char 4) short 5) int 6) long 7) float 8) double

Pass by Reference

All objects created in Java. class C1{

void add(String s){ s.concat("new");

}

}

String s1 = "str";

C1 c = new C1( ); c.add(s1);

In this example, s1 used to point at a block in memory containing "str".

Later, both s1 AND s will point to a block in memory containing "strnew".

This is because of "pass by reference".

OBJECTS have methods to them. PRIMITIVE TYPES cannot have methods

INHERITANCE

Something that gets passed from generation to generation. You only inherit from

PARENTS.

Parent class: a class is a parent if and only if it has a child.

Let C1 be a parent class C2 extends C1{

By extending C1, C2 becomes a child, making C1 a parent. "extends" is another keyword in Java.

HIERARCHY

Object

|_

C1

|_

C2

C2 extends C1 and C1 extends Object. Object is a built-in class that comes with the Java virtual machine.

There is an "is a" relationship as you proceed up the Hierarchy. C2 is a C1. And C1 is an

Object.

The "is a" relationship is transitive (i.e. a -> b & b -> c, therefore a -> c).

Hence, C2 is an Object.

ACCESS MODS public: most scope. Everyone has access. protected: the class, classes in the package, and the children all have access.

< package >: classes in the package only have access to it. private: least scope. The class itself only has access.

< package > is the DEFAULT access mod and therefore it is NEVER written/indicated. When we don't indicate an access mod before a class, Java automatically makes it a < package > access class.

A 'package' statement is the very first line to a code. You can only have comments before a package statement.

Eg. package csula.cs212; public class C2 extends C1{

Here, "package" is a keyword corresponding directly to a folder hierarchy on the computer. This is not the same "package" that we discussed to be an access mod.

If a class is public, it must exist in a file with the same name. package csula.cs212; public class C2 extends C1{

}

This class MUST be in a file called "C2.java", in a folder called "cs212", in a folder called

"csula".

INTERFACE

C++ makes multiple inheritance possible. However, in Java, we only have single inheritance. The purpose of an interface is to make multiple inheritance virtually possible in Java.

In Java,

We extend ONE class.

We implement MULTIPLE interfaces.

package csula.cs212; public class C2 extends C1 implements I1{

public void mult ( ) {

}

} interface I1{

public void mult ( );

}

1) you must implement every method defined in your interface for your code to work.

2) you CAN have an empty method, it just won't do anything.

An interface is a GUARANTEE that you will implement a certain method. As long as you implement the methods, you can have as many interfaces as you want.

An abstract class is a close relative to an interface. The only difference is that an abstract class is a class.

What does abstract mean in Java?

1) it cannot be instantiated

2) it must have at least ONE abstract method.

Eg. (Abstract method)

abstract void div ( );

A class is abstract if and only if it has at least one abstract method.

An abstract method does not have any implementation. abstract class AC1{

abstract void div ( );

void sub(int i) { i=i-3;

}

}

If another class extends an abstract class, it must either 1) override all the abstract methods in the class, or 2) be declared as an abstract class.

public class C2 extends AC1 implements I1{ public void mult ( ){

} void sub(int i){

} i=i-5;

You override the abstract method by calling the name of the method, matching the number of parameters and types, and then by implementing the method within your brackets {}.

Q: Can we instantiate an abstract class?

No.

Q: Why can't we?

It doesn't make sense to instantiate methods that have no implementation.

Interfaces CANNOT EXTEND classes. (It should make sense why.)

Let's look at our hierarchy here:

I1

:..

AC1

|_

C2

Here, the interface is a virtual parent of AC1. AC1 is an I1; C2 is an AC1; therefore C2 is an I1. interface I1{ public void mult ( );

}

// I cannot instantiate AC1 because it is abstract.

AC1 ac;

// CAN'T DO THIS: ac = new AC1( );

// therefore we do the following: ac = new C2 ( );

WHY?

Because C2 is an AC1, we can insantiate a C2 instead of instantiating an AC1. Remember, C2 extends AC1.

AC1 ac; ac = new C2 ( );

C2 c = new C2 ( );

-------------------------------------

Let us go one step further: class C3 extends AC1{ void div ( ){

}

}

AC1 ac;

if (…) { ac = new C2 ( );

// here, we can create a C2 object

} else{ ac = new C3 ( );

// here, we create a C3 object

} ac.div ( );

If the "if condition" is met, ac becomes an instance of C2;

Bottom line calls the C2 div method.

If the "else condition" is met, ac becomes an instance of C3;

Bottom line calls the C3 div method.

GUI (Graphical User Interface):

There are two graphics components in Java. java.awt

(contain Layout Managers) java.swing

Layout Managers:

1) BoarderLayout:

The frame is broken down in 5 different areas.

NORTH

W E

E CENTER A

S S

T T

When add JButton to the north or the south block, the height is acknowledged, but not the width.

In other words, height stays the same, but width will change to fit the whole area.

When add JButton to the east or the west block, the width is acknowledged, but not the height. In other words, width stays the same, but height will change to fit the whole area.

SOUTH

When add JButton to the center, neither the height nor the width is acknowledged. Both heights and width will change to fit the whole area.

2) GridLayout

It consists of rows and columns.

Ex.

The following consists of 3 rows and 2 columns.

1 2

3 4

5 6

It splits evenly. When component is added, neither the width nor heights is acknowledged. It will fill up the entire space.

3) FlowLayout

When the first component is added, it stays at the middle of the first row. When the second component is added, the area will splint in the middle and the component will be placed in the first row as well. It will continue doing so until the first row is filled up, then it will change to the second row.

Both the width and height are acknowledged. They will remain the same.

Ex.

4) CardLayout

It has multiple internal frames

Ex.

What is a Thread?

A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently of everything else that might be happening. A thread is like a classic program that starts at point

A

and executes until it reaches point

B

. It does not have an event loop. A thread runs independently of anything else happening in the computer. Without threads an entire program can be held up by one CPU intensive task or one infinite loop, intentional or otherwise. With threads the other tasks that don't get stuck in the loop can continue processing without waiting for the stuck task to finish.

It turns out that implementing threading is harder than implementing multitasking in an operating system. The reason it's relatively easy to implement multitasking is that individual programs are isolated from each other. Individual threads, however, are not. To return to the printing example, suppose that while the printing is happening in one thread, the user deletes a large chunk of text in another thread. What's printed? The document as it was before the deletion? The document as it was after the deletion? The document with some but not all of the deleted text? Or does the whole system go down in flames? Most often in a non-threaded or poorly threaded system, it's the latter.

Threaded environments like Java allow a thread to put locks on shared resources so that while one thread is using data no other thread can touch that data. This is done with synchronization .

Synchronization should be used sparingly since the purpose of threading is defeated if the entire system gets stopped waiting for a lock to be released. The proper choice of objects and methods to synchronize is one of the more difficult things to learn about threaded programming.

How Java Uses Threads

Java applications and applets are naturally threaded. The runtime environment starts execution of the program with the main()

method in one thread. Garbage collection takes place in another thread. Screen updating occurs in a third thread. There may be other threads running as well, mostly related to the behavior of the virtual machine. All of this happens invisibly to the programmer. Some of the time you're only concerned with what happens in the primary thread which includes the main() method of a program. If this is the case you may not need to worry about threading at all.

Sometimes, however, you need to add your own threads to an applet or application. The simplest reason for adding a separate thread is to perform a long calculation. For instance if you're trying to find the ten millionth prime number, you probably don't want to make users twiddle their thumbs while you search. Or you may be waiting for a resource that isn't available yet, a large graphic to download from the Internet, for example. Once again you shouldn't make the user wait while your program waits. Any operation that is going to take a noticeable period of time should be placed in its own thread.

The other reason to use threading is to more evenly divide the computer's power among different tasks. If you want to draw random rectangles on the display, you would still like the applet to respond to user input. If all the CPU time is spent drawing rectangles, there's nothing left over for the user. On a preemptively multitasking operating system like Solaris or Windows NT, the user may at least be able to kill the application. On a cooperatively multitasking operating system like MacOS 9 or Windows 9x, the user may have to reboot their machine. This is a bad thing.

With threads you can set the priority of different processes, so that user input receives a high priority and drawing pretty pictures receives a low priority. Then the user can stop the applet without flipping the power switch on their machine.

When you typing in Microsoft word you thing just typing but on background another program run it is spelling and Grammar check at same time.

Same in eclipse, checking error if we have error in typing

The processor execute one instruction at the same time

1 GHz = 230 Hz Frequency/per Second

In this example we have 4 processes

P1 P2 P3 P4

………

………

………

………

………

When done another start to process it depend to operating system to give how long takes for process for example we can change to 10 N/S. we can change our priority system time.

How we can write or read thread on our program?

We have 3 key terms

1.

Lock: meaning like English language lock one place. For example user require to use printer we must check nobody use this printer after that we can use printer but if somebody use it here lock show up.

2.

Semaphore: nothing more than counter, go up V, go down P

On printer we have Semaphore

printer.p();

Semaphore has one lock. Memory.p(); // 5 5-1=4 to write to memory

In Semaphore we can’t count negative, just we count positive number. If we arrive to zero process goes to sleep until one of the other process call V and then process weak up and add another

3.

Monitor:

Work like Semaphore. A monitor is an object with some built-in mutual exclusion and thread synchronization capabilities. They are an integral part of the programming language so the compiler can generate the correct code to implement the monitor. Only one thread can be active at a time in the monitor, where ``active'' means executing a method of the monitor.

Monitors also have condition variables, on which a thread can wait if conditions are not right for it to continue executing in the monitor. Some other thread can then get in the monitor and perhaps change the state of the monitor. If conditions are now right, that thread can signal a waiting thread, moving the latter to the ready queue to get back into the monitor when it becomes free.

Wait

if wait release all other locks

Sleep

if calls sleep hold on to all other locks

Start

Ready

Ready to execute

If not finish

Switch to CPU

Until some body finish the job

Running

When finish

Executing

Wait/Sleep Dead

The Thread Classes

Java has two ways a program can implement threading. One is to create a subclass of java.lang.Thread

. However sometimes you'll want to thread an object that's already a subclass of another class. Then you use the java.lang.Runnable

interface.

The Thread class has three primary methods that are used to control a thread: public void start() public void run() public final void stop()

The start() method prepares a thread to be run; the run() method actually performs the work of the thread; and the stop() method halts the thread. The thread dies when the run() method terminates or when the thread's stop() method is invoked.

You never call run() explicitly. It is called automatically by the runtime as necessary once you've called start() . There are also methods to suspend and resume threads, to put threads to sleep and wake them up, to yield control to other threads, and many more. I'll discuss these later.

The Runnable interface allows you to add threading to a class which, for one reason or another, cannot conveniently extend Thread. It declares a single method, run() : public abstract void run()

By passing an object which implements Runnable to a Thread() constructor, you can substitute the

Runnable 's run() method for the Thread 's own run() method. (More properly the Thread object's run() method simply calls the Runnable 's run() method.)

5 philosophy problem:

Just can think or eat. Have two chop stick.

Problem

In 1965, Dijkstra posed and solved a synchronization problem called the dining philosophers problem.

The problem can be stated as follows. Five philosophers are sitting around a table. Each philosopher has a plate of spagetti. A philosopher needs two forks to eat it. There is a fork between each couple of plates.

The life of a philosopher consists of alternate periods of eating and thinking. When a philosopher gets hungry, he/she tries to acquire his/her left and right forks, one at a time, in either time. If successful in acquiring two forks, a philosopher eats for a while, then puts down the forks and continues to think. The key question is: can you write a program for each philosopher that does what it is supposed to do and never gets stuck? Unfortunately, there may be situation when all five philosophers take their left forks simultaneously. None will be able to take their right forks, and there will be a deadlock. Deadlock is a situation when all processes would stay blocked forever and no more work would be done. One of the suggestions is that after taking the left fork, the program checks top see if the right fork is available. If it is not, the philosopher put down the left one, waits for some time, and then repeats the whole process. But it is not a good solution, since all the philosophers could start the algorithm simultaneously, picking up their left forks, seeing that their right forks were not available, putting down their left forks, waiting, etc., forever. A situation like this is called starvation . But if the philosophers would just wait a random time instead of the same time after falling to acquire the right-hand fork, the chance that everything would continue in lockstep for even an hour is very small. One way to avoid deadlock and starvation is by use a semaphore type variable MUTEX. Before to acquire forks, a philosopher would do a DOWN an MUTEX.

After replacing the forks, she would do an UP on MUTEX. From a practical one, it has a performance bug: only one philosopher can be eating at any instant. With five forks available, we should be able to allow two philosophers to eat at the same time. Let us consider the method, which allows the maximum parallelism for arbitrary number of philosophers. It uses as array to keep track of whether a philosopher is eating, thinking or hungry. State if neither neighbors eating. Note that each philosopher has two neighbors: left and right. The program uses an array of philosophers, one per philosopher, so hungry philosophers can be blocked if the needed forks are busy. A Petri net describing the problem is illustated in Fig.4.1. In this figure pleces E1, ... E5 correspond to EATING state of the philosophers. A token in any of these places means relevent philosopher is at EATING state. Similarly, a token in any of the states T1 through T5 indicates that corresponding philosopher is at THINKING state. Places F1 through F5 are used to keep track of presence/absense of the forks. If fork is available then corresponding place must contain a token. CPN model described above is fully adequate to the nature of Dining Philosophers

Problem. The solutions of the problem can be easily obtained by firing relevant transitions of the Petri net.

P2

C2 C3

P1

C1

C4

P3

C5

We don’t have starvation – dead lock

Pi wants to eat take chopstick Ci

Pi

Ci

Except p5

C1

In this case one people can eat.

P5

P4

Thread in java:

{

Extends thread

Implement run able

Example:

Calss Test extend thread

Two way create thread in java

Public void run()

{

}

Public static void main (String[] args)

}

{

Test t = new Test(); t.start(); // takes no parameters

{

}

** Java has single inheritance calss Test implements Runnable

Public void run()

{

}

Public static void main (String[] args)

{

Test t = new Test();

At same time execution

At same time execution

}

Thread th = new thread(t); // it tacks run able object implementation of run //method

Th.start();

}

Print();

}

Public void run()

{

Public synchronized void print()

}

{

}

Public synchronized int getArray()

{

}

Test t = new test(); t.start(); t.print();

Download