Presentation is loading. Please wait.

Presentation is loading. Please wait.

SCJP 9/10 Threads.

Similar presentations


Presentation on theme: "SCJP 9/10 Threads."— Presentation transcript:

1 SCJP 9/10 Threads

2 Exam objectives Start new threads
Recognize thread states and transitions Use object locking to avoid concurrent access Write code that uses wait(), notify(), notifyAll()

3 Starting new thread java.lang.Thread Start()
Yield() // yield – poddawać się, uginać się Sleep() Run() Extending vs. java.lang.Runnable

4 thread.run Thread t = new Thread();
t.run(); // legal but doesn't start a new thread

5 Many threads Runnable mr = new MyRunnable();
Thread t1 = new Thread(mr); Thread t2 = new Thread(mr); Thread t3 = new Thread(mr); t1.start(); t2.start(); t3.start();

6 The order in which threads are chosen to run is not guaranteed.

7 Thread states

8 Thread states Sleeping, waiting or blocked on object's lock
new Thread() start() Scheduler decision After run()

9 Sleep() and yield() are static. They always affect current thread

10 Sleep(milisec) is the minimum duration in which thread will not run
Sleep(milisec) is the minimum duration in which thread will not run. Can take longer

11 Priorities Don't rely on thread priorities (Thread.setPriority()). It's information for schedules. Thread get's the same priority as the one in which it was created Yield() - hold back to allow other threads of the same priority

12 Join Thread t = new Thread(); t.start(); t.join()
What does this code do?

13 t.join() = „Join me (the current thread) to the end of t, so that t finishes before me

14 Synchonization Keyword synchronized Synchronizing methods or blocks
void synchronized doStuff() {…} synchronized (object) {…} Synchronization based on object lock. Every object has only one lock.

15 Method vs. block int synchronized doStuff() { return 10; }
Is equivalent to int doStuff() { synchronized (this) { return 10; }

16 Locking static methods
Every class also has a lock. static synchronized int doStuff() { return 10; } Is equivalent to static int doStuff() { synchronized (MyClass.class) { return 10; }

17 „Thread-safeness” StringBuffer (StringBuilder is NOT)
Collections.synchronizedList/Set/Map()

18 Not safe thread-safe collections
List list = Collections.synchronisedList(new ArrayList()); // is this safe? If (list.size() > 0) { list.remove(0); }

19 Thread interaction wait() - tell others that I'm waiting
notify()/notifyAll() - tell others that I can get back to work

20 Wait(), notify(), notifyAll() is always called from within a synchonized block

21 java.lang.Object. Be sure to know what comes from Object, Runnable and Threadow what comes from Object, Runnable and Thread

22 The End :-)

23 Thread get's the


Download ppt "SCJP 9/10 Threads."

Similar presentations


Ads by Google