1 Java - Threads b b A thread is an individual flow of control within a larger program. b b A...

31
1 Java - Threads Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded. You can think of threads as the ability of your program to do multiple independent actions at the same time where each action runs in its own thread. Each thread can be controlled (started, stopped, prioritised) individually.
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    216
  • download

    0

Transcript of 1 Java - Threads b b A thread is an individual flow of control within a larger program. b b A...

1

Java - ThreadsJava - Threads

A thread is an individual flow of control within a larger program.

A program which is running more than one thread is said to be multithreaded.

You can think of threads as the ability of your program to do multiple independent actions at the same time where each action runs in its own thread. Each thread can be controlled (started, stopped, prioritised) individually.

2

ThreadsThreads

Unlike separate programs, threads within the same class share data members making it easy for them to work co-operatively.

3

No ThreadsNo Threads

import java.awt.Graphics;import java.awt.Graphics;

import java.util.Date;import java.util.Date;

public class Clock extends public class Clock extends java.applet.Appletjava.applet.Applet

4

No ThreadsNo Threads

public void start( ) {public void start( ) {

while ( true ) {while ( true ) {

repaint( );repaint( );

try try {clockThread.sleep( 1000 );}{clockThread.sleep( 1000 );}

catch ( Exception e catch ( Exception e ) {}) {}

}}}}

5

No ThreadsNo Threads

public void paint( Graphics g ) {public void paint( Graphics g ) {

Date now = new Date( );Date now = new Date( );

g.drawString(now.getHours( ) + g.drawString(now.getHours( ) + ":" ":"

+ now.getMinutes( )+ ":"+ now.getMinutes( )+ ":"

+ now.getSeconds( ), + now.getSeconds( ), 5,10);5,10);

}}

6

ThreadsThreads

import java.awt.Graphics;import java.awt.Graphics;

import java.util.Date;import java.util.Date;

public class Clock extends public class Clock extends java.applet.Applet implements java.applet.Applet implements Runnable {Runnable {

Thread clockThread;Thread clockThread;

7

ThreadsThreads

public void start( ) {public void start( ) {

if ( clockThread == null ) if ( clockThread == null ) {{

clockThread = new Thread clockThread = new Thread ( this, "Clock" );( this, "Clock" );

clockThread.start( );clockThread.start( );

}}

}}

8

ThreadsThreads

public void run( ) {public void run( ) {

while ( true ) {while ( true ) {

repaint( );repaint( );

try try {clockThread.sleep( 1000 );}{clockThread.sleep( 1000 );}

catch ( Exception e catch ( Exception e ) {}) {}

}}}}

9

ThreadsThreads

public void paint( Graphics g ) {public void paint( Graphics g ) {

Date now = new Date( );Date now = new Date( );

g.drawString(now.getHours( ) + g.drawString(now.getHours( ) + ":" ":"

+ now.getMinutes( )+ ":"+ now.getMinutes( )+ ":"

+ now.getSeconds( ), + now.getSeconds( ), 5,10);5,10);

}}

10

ThreadsThreads

public void stop( ) {public void stop( ) {

clockThread.stop( );clockThread.stop( );

clockThread = null;clockThread = null;

}}

}}

11

Control StructuresControl Structures

if(grade >= 16)system.out.println( "passed");

else

system.out.println( "failed");

12

Control StructuresControl Structures

switch(grade) {case 'A':

gradeA++;

break;

case 'B': gradeB++;

break;

13

Control StructuresControl Structures

case 'C':gradeC++;

break;

case 'D': gradeD++;

break;

default:showStatus("invalid grade. Enter new grade.");

14

Repetition StructuresRepetition Structures

Whiledo/while for

15

Repetition StructuresRepetition Structures

int i = 2;

while(i <=100)

i = i + 1;

16

Repetition StructuresRepetition Structures

for(int i = 2; i <= 100; i++)

j = j + 1;

17

Repetition StructuresRepetition Structures

int i = 2;

do { i = i + 1;

} while(i <=100)

18

ArraysArrays

Creating an array:

MyObject arrayofobjs[] = new MyObject[10];

add actual MyObject objects to that array:

for (int i=0;

i < arrayofobjs.length; i++) arrayofobjs[i] = new MyObject;

19

Creating Arrays - Creating Arrays - examplesexamples

String[] string Array;String[] string Array;

int[] intArray;int[] intArray;

boolean[] booleanArray;boolean[] booleanArray;

int[] my IntArray = new int[20];int[] my IntArray = new int[20];

int[] numbers = {2, 5, 8, 10};int[] numbers = {2, 5, 8, 10};

20

Input/outputInput/output

Files and StreamsFiles and Streams• System.in System.in - - standard input stream standard input stream

objectobject• System.out - System.out - standard output standard output

stream objectstream object• System.err - System.err - standard input stream standard input stream

objectobject

are three stream object created when are three stream object created when a Java program is executed.a Java program is executed.

21

Input/outputInput/output

To perform file processing in JavaTo perform file processing in Java

java.iojava.io

package must be imported.package must be imported. Stream ClassesStream Classes

• FileInputStremsFileInputStrems - for input from a file - for input from a file

• FileOutputStreamFileOutputStream - for output to a file- for output to a file

22

Object

InputStream OutputStream

FileInputStream FileOutputStream

PipedInputStream PipedOutputStream

Class Hierarchy

23

More on Class HierarchyMore on Class Hierarchy

ObjectObject• FileFile• FileDescriptorFileDescriptor• StreamTokenizerStreamTokenizer• InputStreamInputStream• OutputStreamOutputStream• RandomAccessFileRandomAccessFile

24

More on Class HierarchyMore on Class Hierarchy

InputStreamInputStream• ByteArrayInputStreamByteArrayInputStream• SequenceInputStreamSequenceInputStream• StringBufferInputStreamStringBufferInputStream• PipedInputStreamPipedInputStream• FileInputStreamFileInputStream• FilterInputStreamFilterInputStream

– DataInputStreamDataInputStream– BufferedInputStreamBufferedInputStream– PushBackInputStreamPushBackInputStream– LineNumberInputStreamLineNumberInputStream

25

More on Class HierarchyMore on Class Hierarchy

OutputStreamOutputStream• ByteArrayOutputStreamByteArrayOutputStream• PipedOutputStreamPipedOutputStream• FileOutputStreamFileOutputStream• FilterOutputStreamFilterOutputStream

– DataOutputStreamDataOutputStream– BufferedOutputStreamBufferedOutputStream– PrintStreamPrintStream

26

Input/outputInput/output

PipesPipes• synchronised communication synchronised communication

channels between threadschannels between threads• One thread send data to another by One thread send data to another by

writing to a writing to a PipedOutputStream.PipedOutputStream.• The target thread reads information The target thread reads information

from the pipe via a from the pipe via a PipedInputStreamPipedInputStream

27

Creating a FileOutputStream Creating a FileOutputStream object and attempting to open a object and attempting to open a file:file:

try {try {

output = new DataOutputStream(output = new DataOutputStream(

new FileOutputStream(“afile.dat”));new FileOutputStream(“afile.dat”));

}}

catch ( IOException e ) {catch ( IOException e ) {

System.err.println(“File not opened System.err.println(“File not opened properly\n” + e.toString());properly\n” + e.toString());

System.exit( 1 );}System.exit( 1 );}

28

Writing to a fileWriting to a file

output.writeInt ( accountNumber);output.writeInt ( accountNumber);

output.writeDouble(doubleValue);output.writeDouble(doubleValue); Closing the fileClosing the file

output.close();output.close();

29

Opening a file to readOpening a file to read

try {try {

input = new DataInputStream(input = new DataInputStream(

new FileInputStream(“afile.dat”));new FileInputStream(“afile.dat”));

}}

catch ( IOException e ) {catch ( IOException e ) {

System.err.println(“File not opened System.err.println(“File not opened properly\n” + e.toString());properly\n” + e.toString());

System.exit( 1 );}System.exit( 1 );}

30

Reading from a fileReading from a file

Account = input.readInt();Account = input.readInt();

balance = input.readDouble();balance = input.readDouble();

input.close();input.close();

31

Read/WriteRead/Write

And of courseAnd of course

System.out.print(“Enter grade:”);System.out.print(“Enter grade:”);

grade = System.in.read();grade = System.in.read();