java核心课件-第12章.ppt_第1页
java核心课件-第12章.ppt_第2页
java核心课件-第12章.ppt_第3页
java核心课件-第12章.ppt_第4页
java核心课件-第12章.ppt_第5页
已阅读5页,还剩20页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第12章线程 了解线程在其生命周期中状态的转换 会用两种方法熟练创建线程 能熟练运用同步 12 1线程和进程 现代操作系统都支持多任务 主要有两种形式 基于线程和基于进程 从本质上说 进程就是独立运行的程序 有独立的指令序列 独立的数据空间和资源 线程则是依附于进程存在的独立的指令序列 一个进程中可以有多个线程 这些线程共享进程的数据和资源 线程有独立的生命周期 因为没有存储空间的交换 线程间的切换优于进程 因此尽量用多线程 Java中线程分为 用户线程和守护线程 特点如下 用户线程可以转换为守护线程 转换时机只有在新建态和终止态进行 守护线程运行于系统后台 一般是为用户线程服务 用户线程运行于系统前台 当所有的用户线程都终止时 JVM会杀死守护线程 单线程实例 classSingleThread privateStringid publicSingleThread Stringstr id str publicvoidrun for inti 0 i 4 i for intj 0 j 100000000 j System out println id isrunning classTest publicstaticvoidmain Stringargs SingleThreaddog newSingleThread doggy SingleThreadcat newSingleThread kitty dog run cat run 12 2线程的状态及其生命周期 新建态 用new语句创建一个Thread对象时 该状态的线程不会立即被执行 但会分配系统资源 就绪态 当线程调用start方法后 CPU会为其分配相应的时间 这时线程就绪了 运行态 当线程内的代码块开始执行时 该线程便开始运行 一旦线程开始运行 它不必始终保持运行状态 因此很多书中把就绪态和运行态统称为可运行状态 阻塞 挂起态 有人调用该线程的sleep 方法 该线程调用了wait方法 该线程试图锁定一个当前被另一个线程锁定了的对象 有人调用了该线程的suspend方法 终止状态 由于run方法的正常退出而自然死亡 没有抓取到的异常事件终止了run方法的执行 从而导致线程突然死亡 有人调用了该线程的stop方法 12 3线程的优先级 对新建的线程通常继承其父类的优先级 用户可以通过setPriority方法来修改系统自动设定的线程优先级 线程优先级的使用原则是与系统有着密切关系的 当JVM取决于主机平台的线程机制时 线程的调度完全受线程机制的支配 12 4线程的创建 Thread类 它是线程类的超类 它是一个线程有生命周期 继承它的类本身也是一个线程 Runnable接口 它只定义了线程的行为 由实现其run方法来实现 但它没有线程的生命周期 实现它的类本身不是一个线程 启动线程时 都应调用线程的start方法 12 4 1继承Thread类 覆盖其run方法 其余方法继承Thread的 classMultThreadextendsThread privateStringid publicMultThread Stringstr id str publicvoidrun for inti 0 i 4 i for intj 0 j 100000000 j System out println id isrunning classTest publicstaticvoidmain Stringargs MultThreaddog newMultThread doggy MultThreadcat newMultThread kitty dog start cat start 注意在上页的程序代码中 不能直接调用run方法 这样只是把run方法运行一遍而已 并没有激活线程 正确的方式是调用由Thread类继承而来的start方法 然后由这个方法在计划表 scheduler 中登录这个线程 最后这个线程开始运行时 run方法自然会被调用 不管是继承Thread创建线程 还是实现Runnable接口创建线程 都应该调用start方法启动线程 由结果可以看出 这两个线程是一起运行的 但哪一个字符串先出现则不一定 看谁抢到CPU的资源 12 4 2实现Runnable接口 classRunnableThreadimplementsRunnable privateStringid publicRunnableThread Stringstr id str publicvoidrun for inti 0 i 4 i for intj 0 j 100000000 j System out println id isrunning classTest publicstaticvoidmain Stringargs RunnableThreaddog newRunnableThread doggy RunnableThreadcat newRunnableThread kitty Threadt1 newThread dog Threadt2 newThread cat t1 start t2 start 当一个类已经继承了另一个类时 可通过实现Runnable接口创建线程 用实现Runnable接口创建线程时 可以使多个线程共享同一资源 用实现Runnable接口创建线程时 因为本类没有线程的生命周期 因此必须新建一个线程 12 5Thread类 classMultThreadextendsThread privateStringid publicMultThread Stringstr id str publicvoidrun for inti 0 i 4 i try sleep 1000 catch InterruptedExceptione e printStackTrace System out println id isrunning classTest publicstaticvoidmain Stringargs MultThreaddog newMultThread doggy MultThreadcat newMultThread kitty dog start cat start System out println main methodfinished sleep方法抛出了一个检查性异常 必须捕获或向上抛出 yield方法 classMultiThread publicstaticvoidmain String args MyThreadmt newMyThread mt start intindex 0 while true if index 1000 break System out println main classMyThreadextendsThread publicvoidrun while true System out println MyThread yield join方法可以使线程按顺序输出这和单线程的效果一样 一般不用 publicstaticvoidmain Stringargs MultThreaddog newMultThread doggy MultThreadcat newMultThread kitty dog start try dog join catch InterruptedExceptione e printStackTrace cat start try cat join catch InterruptedExceptione e printStackTrace System out println main methodfinished 通过多线程实现龟 Tortoise 兔 Rabbit 赛跑 赛程为1000米 兔子每100毫秒跑100米 乌龟每100毫秒跑10米 当兔子跑到900米时开始睡觉 乌龟跑到终点时 唤醒兔子 publicclassTortoiseimplementsRunnable privateThreadr publicTortoiseB Threadr this r r publicvoidrun for inti 0 i 1000 i 10 System out println 乌龟 i try Thread sleep 100 catch Exceptione if i 1000 try System out println TortoiseisWinner System out println Rubbitawake r resume catch Exceptione publicclassRubbitimplementsRunnable publicvoidrun for inti 0 i 1000 i 100 System out println 兔子 i try Thread sleep 100 catch Exceptione if i 900 System out println Rubbitbegintosleep try Thread currentThread suspend catch Exceptione System out println RubbitistheLoser publicclassGame publicstaticvoidmain String args Rubbitrubbit newRubbit Threadr newThread rubbit Tortoisetortoise newTortoise r Threadt newThread tortoise r start t start System out println Ready Go 12 7线程的同步 多线程为它们共享统一资源提供了机会 当多个线程需要共享资源时 必须保证一个线程不会改变另一个线程使用的资源 同步的基本思想就是避免多个线程同时访问同一资源 classSellThreadimplementsRunnable inttickets 100 publicvoidrun while true if tickets 0 try Thread sleep 10 catch InterruptedExceptione e printStackTrace System out println Thread currentThread getName selltickets tickets tickets classTicketsSystem publicstaticvoidmain String args SellThreadst newSellThread Threadt1 newThread st Threadt2 newThread st Threadt3 newThread st Threadt4 newThread st t1 start t2 start t3 start t4 start 没有同步时的情况 同步方法 方法声明时加上synchronized关键字此时锁的是类的当前对象 this classSellThreadimplementsRunnable inttickets 100 publicvoidrun while true sell publicsynchronizedvoidsell if tickets 0 try Thread sleep 10 catch InterruptedExceptione e printStackTrace System out println Thread currentThread getName selltickets tickets tickets 同步块 锁某一对象语法 synchronized 对象 实现语句 classSellThreadimplementsRunnable Objectobj newObject inttickets 100 publicvoidrun while true synchronized obj if tickets 0 try Thread sleep 10 catch InterruptedExceptione e printStackTrace System out println Thread currentThread getName selltickets tickets tickets wait 和notify wait 方法和notify 方法都是Object类中的方法 用对象来调用 当调用某对象的wait 方法时 当前线程进入该对象的等待队列中 当调用某对象的notify 方法时 唤醒该对象等待队列中的某个线程 这两个方法的调用通常放在同步方法或同步块中 要求实现Runnable接口 编程实现测试打字速度的GUI界面的应用程序importjava awt importjava awt event publicclassTextTestextendsFrameimplementsRunnable ActionListener Panelp1 p2 LabeltestLabel timeLabel scoreLabel TextAreata ButtonstartButton inti 10 publicTextTest p1 newPanel p2 newPanel p1 setLayout newGridLayout 2 1 p2 setLayout newGridLayout 2 1 testLabel newLabel 测字软件 Label CENTER timeLabel newLabel 剩余时间 10 秒 scoreLabel newLabel 成绩 字 分 startButton newButton 开始 ta newTextArea 30 50 ta setEditable false p1 add testLabel p1 add timeLabel p2 add scoreLabel p2 add startButton ad

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论