Presentation is loading. Please wait.

Presentation is loading. Please wait.

MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )

Similar presentations


Presentation on theme: "MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )"— Presentation transcript:

1 MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )

2 Buffered IO IO is usually the bottleneck of a program. So it is important to make the IO process more efficient. Buffered IO means that there is a buffer between the source of data and the sink of data. So data from the source can be moved to the buffer first and wait for the user to get. Without the buffer, then a read request will be directly sent to the source of data and then the data would be returned. With the buffer, the request would first check whether the data is available from the buffer first. If the data is available in the buffer, then there is no need to get the data from the source and time is saved.

3 Buffered IO The same applies to the writing process where output is sent to a buffer first. Then a chunk of data will be send to the output in one go. This would be more efficient then sending the data directly to the output.

4 BufferedInputStream, BufferedReader As the names imply, they are for providing buffered input for binary data or text. They require an exisiting InputStream or an existing Reader to create. One interesting method of BufferedReader is: – public String readLine() which reading a String until either a newline character or EOF is reached.

5 BufferedInputStream BufferedInputStream input=new BufferedInputStream(new FileInputStream("c:/abc.dat"));

6 BufferedReader BufferedReader input=new BufferedReader(new FileReader("c:/abc.dat"));

7 BufferedOutputStream, BufferedWriter These two are to provide buffered output for binary data and text respectively. They need to have an existing OutputStream or an existing Writer to create.

8 BufferedOutputStream BufferedOutputStream output=new BufferedOutputStream(new FileOutputStream("c:/abc.dat"));

9 BufferedWriter BufferedWriter output=new BufferedWriter(new FileWriter("c:/abc.dat"));

10 Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs with only one thread. In other words, these single threaded programs would only do one thing at a time. A program with many threads would be one that can do many things at the same time. For example, it can read a file, do some calculation at the same time.

11 Threads When you run a Java program, a thread is used to execute statements in the main method.

12 Threads However, there are other threads that you may not aware. For example, if your program has a button and you have added an ActionListener, then there is a thread that is going to execute some statements when you press the button.

13 Threads In all Java programs, there is a thread to collect garbage. So although you think that you are writing a single threaded Java program, there are more than one thread in it.

14 Life cycle of a thread

15 Thread Some threads are created by the Java runtime system. For example, the garbage collection thread, the thread that executes the statements of the main method, the thread that handle listeners. However, you can also create your own threads.

16 Threads Thread is a Java class that represents a thread. When you create a thread using the statement: Thread thread=new Thread(); it enter the Born state in the last figure.

17 Thread When the start method of a thread is invoked, it enters the Ready state. When the a CPU is assigned to the Thread, it enters the Running state and the statements defined in the run method of the thread would be executed. When the time allocated for the thread has finished, the thread goes back to Ready state.

18 Thread When the static sleep method of Thread is executed, the current thread would go to the Sleep state and the CPU would stop executing the statements in the run method. When the prescribed time for stopping has expired, the thread would go back to the ready state.

19 Thread When the thread is executing wait method of an object, it enters the wait state and it will stop exection. When some other thread invoke the notify or notifyAll method of the object, the thread would go back to the ready state.

20 Thread When the thread is trying to do some IO but is blocked, it enter the Blocked state. When the IO is finally finished, it goes back to the ready state again. When the thread has finished executing all the statements in the run method, it enters the Death state.

21 Methods of Thread public void run(): The statements in this method would be executed when the thread is in the Running state. You would not invoke this method directly. The method would be invoked when you invoke the start method. The original run() method of Thread contains nothing. So you need to override this method to whatever you want this thread to do for you.

22 Methods of Thread public void start(): This method is used to change a thread from the Born state to the Ready state. Then, if a CPU is available, the statements in the run() method would be executed.

23 public class TestThread extends Thread { /** Creates a new instance of TestThread */ public void run() { for (int i=0;i<10;i++) { double sum=0; for (int j=0;j<1000;j++) { for (int k=0;k<1000;k++) { sum+=Math.sin(i+j+k); } System.out.println("thread: "+sum); }

24 public static void main(String st[]) { TestThread aThread=new TestThread(); //thread enters the Born state aThread.start(); //thread enters the Ready state. for (int i=0;i<10;i++) { double sum=0; for (int j=0;j<1000;j++) { for (int k=0;k<1000;k++) { sum+=Math.sin(i+j+k); } System.out.println("main: "+sum); } }

25 main: -0.025189987251292567 thread: -0.025189987251292567 main: 0.7871690307421841 main: 0.8758084720864001 thread: 0.7871690307421841 main: 0.15923364319459674 thread: 0.8758084720864001 main: -0.7037398629077654 main: -0.9196981845149624 thread: 0.15923364319459674 main: -0.29009023668378703 main: 0.6062253369356854 thread: -0.7037398629077654 main: 0.9451801315255973 thread: -0.9196981845149624 main: 0.41514067211553857 thread: -0.29009023668378703 thread: 0.6062253369356854 thread: 0.9451801315255973 thread: 0.41514067211553857

26 Thread Interesting observations in last program: – the run method has never been called in the program. However, we can see that the statements in the run method have been executed. – the statements in the run method are interleaved with statements the main method. It is a proof that there are two flows of control, or two threads.

27 currentThread In last example, you actually encounter two threads, one is created by the programmer and is called aThread in the program. The other thread is the thread that executes the statements in the main method.

28 currentThread Since you have the reference aThread refers to the first thread, you can do whatever you want to aThread directly. However, how can you do something about the thread that executes the main method? The answer is the static method currentThread of Thread.

29 currentThread In anywhere in your program, if you execute the statement: Thread cThread=Thread.currentThread(); then cThread refers to the thread that is currently executing this statement.

30 sleep sleep is a static method of Thread. When you execute this method, the current thread would go to sleep for certain period. The method is a static method which means that you can only ask yourself to sleep, not others.

31 sleep Now, assume that threadA is executing the statement threadB.sleep(1000) and threadB is executing the print statement. threadA:..... threadB.sleep(1000);...... threadB:..... System.out.printf("abcd");.....

32 sleep Which thread would go to sleep? Although we have executed the sleep statement in the form: threadB.sleep(1000); However, sleep is a static method, therefore it will not affect threadB. In fact, this method will only affect the current thread. Now, this statement is executed by threadA, therefore it is threadA that is going to sleep, not threadB.

33 sleep So actually, the statement: threadB.sleep(1000); is better replaced by Thread.sleep(1000); to avoid misunderstanding. In some textbooks, they write statement like this: Thread.currentThread().sleep(1000); which is again not necessary.

34 sleep the definition of the sleep method is: public static void sleep(long millis) throws InterruptedExceptionInterruptedException The method would throw InterruptedException when some other threads interrupt this sleeping thread.

35 interrupt Unlike sleep which is a static method, interrupt is a non-static method of Thread. This means that you need to get hold of a thread before you can interrupt it.

36 interrupt Assume that a thread A is interrupting a thread B. If thread B is sleeping, then, the InterruptedException would be thrown to thread B. So control of thread B will be passed to the exception handler. Note that thread A would not receive any exception.

37 Thread A:..... threadB.interrupt();..... Thread B:.... try { Thread.sleep(10000); } catch (InterruptedException e) {..... }...... Assume that Thread B is now sleeping at the Thread.sleep(10000) statement and Thread A is now executing the threadB.interrupt() statement. Then, Thread B would then throw an InterruptedException and control of Thread B would go the catch block. However, Thread A would not throw any exception and control would flow to the statement after threadB.interrupt().

38 Interrupting a thread Note that when thread A interrupts thread B but thread B is not sleeping or waiting, then thread B will not be affected in any way except that it has an internal flag to record that someone has interrupt it. There are two ways to check that a thread has been interrupted.

39 interrupted public static boolean interrupted(): again this method is a static method which means that we can only use it to check whether the current thread has been interrupted. After this call, the internal flag would be set to false again so the second call to this method would return false unless the thread is interrupted again.

40 isInterrupted public boolean isInterrupted(): note that this method is not static which means that we can check whether a particular thread has been interrupted or not, not only the current thread. The internal flag that record whether the thread has been interrupted would not be changed after this call.

41 threadA:..... threadB.interrupt();..... if (threadB.isInterrupted()) {... }... if (threadB.isInterrupted()) {... }... threadB:.... System.out.println("hello");......... if (Thread.interrupted()) {........ } Assume that threadB is executing the print statement when threadA interrupts it. threadB would not be affected in any way except that it has an internal flag to record that it has been interrupted. Then, threadA execute the threadB.isInterrupted() method to check whether threadB has been interrupted. The returned value of the method is true and therefore the statement in the if block would be executed.

42 interrupt and interrupted Then, threadB executes the statement Thread.interrupted() to check whether itself has been interrupted. Again, the returned value is true and therefore the statements in the if block would be executed. However, the internal flag would be set to false again. Then, threadA executes the statement threadB.isInterrupted() again. This time, the returned value is false.

43 Synchronization When more than one threads are making change to an object problems may occur.

44 class TestObject { public int a=0; public void addTwo(int id) { int b=a; System.out.println("Thread"+id+":the value of b is "+b); try {Thread.sleep(1000); } catch (Exception e) {} a=b+2; System.out.println("Thread"+id+":the value of a is "+a); } public class TestThread extends Thread { TestObject object; int id; public TestThread(TestObject obj,int id) {

45 object=obj; this.id=id; } public void run() { for (int i=0;i<4;i++) { object.addTwo(id); } public static void main(String st[]) { TestObject obj=new TestObject(); TestThread thread1=new TestThread(obj,1); TestThread thread2=new TestThread(obj,2); thread1.start(); thread2.start(); }

46 Thread1:the value of b is 0 Thread2:the value of b is 0 Thread1:the value of a is 2 Thread1:the value of b is 2 Thread2:the value of a is 2 Thread2:the value of b is 2 Thread1:the value of a is 4 Thread1:the value of b is 4 Thread2:the value of a is 4 Thread2:the value of b is 4 Thread1:the value of a is 6 Thread1:the value of b is 6 Thread2:the value of a is 6 Thread2:the value of b is 6 Thread1:the value of a is 8 Thread2:the value of a is 8

47 synchronized The problem of last program is that two threads are trying to change the state of an object at the same time and they interfere with each other.


Download ppt "MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )"

Similar presentations


Ads by Google