SCJP 9/10 Threads
Exam objectives Start new threads Recognize thread states and transitions Use object locking to avoid concurrent access Write code that uses wait(), notify(), notifyAll()
Starting new thread java.lang.Thread Start() Yield() // yield – poddawać się, uginać się Sleep() Run() Extending vs. java.lang.Runnable
thread.run Thread t = new Thread(); t.run(); // legal but doesn't start a new thread
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();
The order in which threads are chosen to run is not guaranteed.
Thread states
Thread states Sleeping, waiting or blocked on object's lock new Thread() start() Scheduler decision After run()
Sleep() and yield() are static. They always affect current thread
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
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
Join Thread t = new Thread(); t.start(); t.join() What does this code do?
t.join() = „Join me (the current thread) to the end of t, so that t finishes before me
Synchonization Keyword synchronized Synchronizing methods or blocks void synchronized doStuff() {…} synchronized (object) {…} Synchronization based on object lock. Every object has only one lock.
Method vs. block int synchronized doStuff() { return 10; } Is equivalent to int doStuff() { synchronized (this) { return 10; }
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; }
„Thread-safeness” StringBuffer (StringBuilder is NOT) Collections.synchronizedList/Set/Map()
Not safe thread-safe collections List list = Collections.synchronisedList(new ArrayList()); // is this safe? If (list.size() > 0) { list.remove(0); }
Thread interaction wait() - tell others that I'm waiting notify()/notifyAll() - tell others that I can get back to work
Wait(), notify(), notifyAll() is always called from within a synchonized block
java.lang.Object. Be sure to know what comes from Object, Runnable and Threadow what comes from Object, Runnable and Thread
The End :-)
Thread get's the