




已阅读5页,还剩3页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
SCJP Study Notes: Chapter 9 ThreadsChapter 9 Threads1. Defining,Instantiating and Starting ThreadsIn Java, thread means two different things: o An instance of class java.lang.Thread = is just an objecto A thread of execution = an individual process (a lightweight process) that has its own call stackThe main() method runs in the main threadmost important concept to understand from this entire chapter is this: = When it comes to threads, very little is guaranteed.For exam, need to know: start( ), yield( ), sleep( ), run( )The action happens in the run() method1.1 Defining a ThreadsYou can define and instantiate a thread in one of two ways:o Extend the java.lang.Thread classo Implement the Runnable interfaceExtending java.lang.thread - Extend the java.lang.Thread class. - Override the run() method. class MyThread extends Thread public void run() System.out.println(Important job running in MyThread); limitation = if you extend Thread, you cant extend anything elsecan overloaded run(String s) method, but will be ignored by the Thread class unless you call it yourselfImplementing java.lang.runnableclass MyRunnable implements Runnable public void run() System.out.println(Important job running in MyRunnable); 1.2 Instantiating a ThreadMyThread t = new MyThread()ORMyRunnable r = new MyRunnable();Thread t = new Thread(r);Thread t = new Thread(new MyThread(); / a bit silly but legal- Thread() - Thread(Runnable target) - Thread(Runnable target, String name) - Thread(String name)1.3 Starting a thread t.start();NEW State = RUNNABLE StateWhen the thread gets a chance to execute, its target run() method will runRemember: You call start() on a Thread instance, not on a Runnable instanceSUMMARY class FooRunnable implements Runnable public void run() for(int x =1; x DEAD StateMethod from java.lang.Thread Classpublic static void sleep(long millis) throws InterruptedException public static void yield() public final void join() throws InterruptedException public final void setPriority(int newPriority) Method from java.lang.Object Classpublic final void wait() throws InterruptedExceptionpublic final void notify()public final void notifyAll()2. Thread States and Transitions2.1 Thread States1. NEW - after the Thread instance has been created, but the start() method has not been invoked2. RUNNABLE - its eligible to run, but the scheduler has not selected it- when the start() method is invoked- can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state3. RUNNING - thread scheduler selects it4. WAITING/BLOCKED/SLEEPING - currently not eligible to run- may be blocked waiting for a resource5. DEAD - considered dead when its run() method completes- it can never be brought back to life2.2 Preventing Thread ExecutionA thread may be get kicked out of running because of sleeping/waiting/blocked2.3 SleepingThe sleep() method is a static method of class Threadtry Thread.sleep(5*60*1000); / Sleep for 5 minutes catch (InterruptedException ex) A threads sleep() expires, and it wakes up, does not mean it will return to running! Remember, when a thread wakes up, it simply goes back to the runnable state.2.4 Thread Priorities and yield( ) - Priority: 1-10 (default=5)- thread-scheduling priority behavior is not guaranteedt.setPriority(8);Thread.MIN_PRIORITY (1)Thread.NORM_PRIORITY (5)Thread.MAX_PRIORITY (10)yield( ) Method:make the currently running thread head back to runnable to allow other threads of the same priority to get their turnA yield() wont ever cause a thread to go to the waiting/sleeping/ blocking state. At most, a yield() will cause a thread to go from running to runnable, but again, it might have no effect at all.join( ) Methodnon-static join() method of class Thread lets one thread join onto the end of another threadThread t = new Thread();t.start();t.join();A running thread could leave the running state:o A call to sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted before its specified time).o A call to yield() Not guaranteedo A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins witho The threads run() method completeso A call to wait() on an objecto A thread cant acquire the lock 3 Synchronizing Code3.1 Synchronization and LocksRace Condition = multiple threads can access the same resource and can produce corrupted data We must guarantee that the two steps of the withdrawal “checking the balance and making the withdrawal” are never split apart = atomicTo protect the data:- Mark the variables private. - Synchronize the code that modifies the variables. private synchronized void makeWithdrawal(int amt) if (acct.getBalance() = amt) System.out.println(Thread.currentThread().getName() + is going to withdraw); try Thread.sleep(500); catch(InterruptedException ex) acct.withdraw(amt); System.out.println(Thread.currentThread().getName() + completes the withdrawal); else System.out.println(Not enough in account for + Thread.currentThread().getName() + to withdraw + acct.getBalance(); weve guaranteed that once a thread (Lucy or Fred) starts the withdrawal process (by invoking makeWithdrawal(), the other thread cannot enter that method until the first one completes the process by exiting the methodEvery object in Java has a built-in lockif one thread has picked up the lock, no other thread can pick up the lock until the first thread releaseso Only methods (or blocks) can be synchronized, not variables or classes. o Each object has just one lock. o Not all methods in a class need to be synchronized. A class can have both synchronized and non-synchronized methodso If a thread goes to sleep, it holds any locks it hasit doesnt release themYou can reduce the scope of the synchronized part to something less than a full methodto just a blockclass SyncTest public void doStuff() System.out.println(not synchronized); synchronized(this) System.out.println(synchronized); public synchronized void doStuff() System.out.println(synchronized); is equivalent to this: public void doStuff() synchronized(this) System.out.println(synchronized); Static methods can be synchronized = need one lock per classpublic static int getCount() synchronized(MyClass.class) / class literalreturn count; o Threads calling non-static synchronized methods in the same class will only block each other if theyre invoked using the same instance. Thats because they each lock on this instance, and if theyre called using two different instances, they get two locks, which do not interfere with each other. o Threads calling static synchronized methods in the same class will always block each other - they all lock on the same Class instance. o A static synchronized method and a non-static synchronized method will not block each other, ever. The static method locks on a Class instance while the non-static method locks on the this instance - these actions do not interfere with each other at all. o For synchronized blocks, you have to look at exactly what object has been used for locking. (Whats inside the parentheses after the word synchronized?) Threads that synchronize on the same object will block each other. Threads that synchronize on different objects will not. In order to make a class thread-safe, methods that access changeable fields need to be synchronizedAccess to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronized methodsStringBuffer and StringBuilder are nearly identical classes, except that all the methods in StringBuffer are synchronized when necessaryStringBuilder is a little bit fasterEven when a class is thread-safe, it is often dangerous to rely on these classes to provide the thread protection you neede.g. dont rely on Collections.synchronizedList(). Instead, synchronize the code yourself3.2 Thread DeadlockTwo threads are blocked, with each w
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 达标测试人教版八年级上册物理《机械运动》必考点解析练习题(含答案详解)
- 大安市辅警笔试真题2025
- 达标测试人教版八年级上册物理声现象《噪声的危害和控制》专项攻克练习题(解析版)
- 2025国考朝阳市知识产权保护岗位行测必刷题及答案
- 2025国考葫芦岛市信访接待岗位行测模拟题及答案
- 2025国考齐齐哈尔市海关监管岗位申论高频考点及答案
- 2025国考石家庄市公安执法岗位行测必刷题及答案
- 2025国考呼和浩特市国土资源岗位申论模拟题及答案
- 难点解析人教版八年级上册物理声现象《声音的特性声的利用》定向测试练习题(含答案详解)
- 达标测试人教版八年级上册物理《声现象》章节测评试题(含答案解析)
- 人员无效走动管理办法
- 小学心理健康课:男生女生的青春期成长
- DB11T 2441-2025 学校食堂清洁和消毒规范
- 职业生涯规划第一课课件
- 弯沉试验培训
- 国家社科基金项目2025年度课题指南
- 公司适用法律法规标准清单2025年08月更新
- 创伤的呼吸道管理
- 护理气压治疗课件
- 医院信息化建设中长期规划(十五五规划2025年)
- 消防隐患教学课件
评论
0/150
提交评论