Thread: Examples

30

Transcript of Thread: Examples

Page 1: Thread: Examples
Page 2: Thread: Examples

This is the simplest application we can write.

What will it require in the way of threads?

Page 3: Thread: Examples

* Thread main

* Thread “Reference Handler (system thread)

Page 4: Thread: Examples

* Basic JFrame

Page 5: Thread: Examples

* Still have our main thread

* Still have our system thread “Reference Handler”

Page 6: Thread: Examples
Page 7: Thread: Examples
Page 8: Thread: Examples
Page 9: Thread: Examples
Page 10: Thread: Examples
Page 11: Thread: Examples

* Notice, the main thread has expired.

* The other threads remain until the GUI expires.

Page 12: Thread: Examples

* Basic class that implements a single thread

* No main method--just a class

Page 13: Thread: Examples

* Reusing our BasicApplication

* Will instantiate one additional thread

Page 14: Thread: Examples
Page 15: Thread: Examples

* Have instantiated new object sal but have not yet created a new thread.

Page 16: Thread: Examples
Page 17: Thread: Examples

* Thread main has died, but the application lives on until the last thread is dead.

Page 18: Thread: Examples

* Now will have two new threads in addition to main

Page 19: Thread: Examples
Page 20: Thread: Examples

* Thread main has expired. But, because of breakpoints, the

two other threads are still alive.

Page 21: Thread: Examples

The Tortoise Versus

the Hare: Example

Page 22: Thread: Examples

First, Tortoise and Hare each must extend

Thread

You do not need to get

this fancy in how you move your Tortoise

or Hare

Page 23: Thread: Examples

You only need to use the Thread method ‘sleep()’

Page 24: Thread: Examples
Page 25: Thread: Examples
Page 26: Thread: Examples

You instantiate Race3 and then call its ‘go()’ method.

Page 27: Thread: Examples

‘go()’ just instantiates Hare and Tortoise and calls their start() methods.

Page 28: Thread: Examples
Page 29: Thread: Examples
Page 30: Thread: Examples