java核心课件第12章

上传人:汽*** 文档编号:567369956 上传时间:2024-07-20 格式:PPT 页数:25 大小:286.02KB
返回 下载 相关 举报
java核心课件第12章_第1页
第1页 / 共25页
java核心课件第12章_第2页
第2页 / 共25页
java核心课件第12章_第3页
第3页 / 共25页
java核心课件第12章_第4页
第4页 / 共25页
java核心课件第12章_第5页
第5页 / 共25页
点击查看更多>>
资源描述

《java核心课件第12章》由会员分享,可在线阅读,更多相关《java核心课件第12章(25页珍藏版)》请在金锄头文库上搜索。

1、第12章 线程v了解线程在其生命周期中状态的转换;v会用两种方法熟练创建线程;v能熟练运用同步12.1 线程和进程v现代操作系统都支持多任务,主要有两种形式:基于线程和基于进程;v从本质上说,进程就是独立运行的程序,有独立的指令序列,独立的数据空间和资源;v线程则是依附于进程存在的独立的指令序列,一个进程中可以有多个线程。这些线程共享进程的数据和资源,线程有独立的生命周期;v因为没有存储空间的交换,线程间的切换优于进程,因此尽量用多线程。vJava中线程分为:用户线程和守护线程,特点如下:用户线程可以转换为守护线程,转换时机只有在新建态和终止态进行;守护线程运行于系统后台,一般是为用户线程服务

2、,用户线程运行于系统前台,当所有的用户线程都终止时,JVM会杀死守护线程。单线程实例vclass SingleThread private String id;public SingleThread (String str)id = str;public void run() for(int i=0; i4; i+)for(int j=0; j100000000; j+); System.out.println(id+ is running.); class Test public static void main(String args)SingleThread dog = new Sing

3、leThread (doggy); SingleThread cat = new SingleThread (kitty); dog.run(); cat.run();12.2 线程的状态及其生命周期就绪运行死亡阻塞休眠等待start()notify()I/O结束yield()I/O请求stopt()run()结束wait()sleep()notifyAll()分派新建v新建态:用new语句创建一个Thread对象时。该状态的线程不会立即被执行,但会分配系统资源;v就绪态:当线程调用start方法后,CPU会为其分配相应的时间,这时线程就绪了;v运行态:当线程内的代码块开始执行时,该线程便开始

4、运行。一旦线程开始运行,它不必始终保持运行状态,因此很多书中把就绪态和运行态统称为可运行状态;v阻塞/挂起态:有人调用该线程的sleep()方法;该线程调用了wait方法;该线程试图锁定一个当前被另一个线程锁定了的对象;有人调用了该线程的suspend方法;v终止状态:由于run方法的正常退出而自然死亡;没有抓取到的异常事件终止了run方法的执行,从而导致线程突然死亡;有人调用了该线程的stop方法。12.3 线程的优先级v对新建的线程通常继承其父类的优先级。用户可以通过setPriority方法来修改系统自动设定的线程优先级。v线程优先级的使用原则是与系统有着密切关系的,当JVM取决于主机平

5、台的线程机制时,线程的调度完全受线程机制的支配。12.4 线程的创建vThread类:它是线程类的超类,它是一个线程有生命周期,继承它的类本身也是一个线程;vRunnable接口:它只定义了线程的行为,由实现其run方法来实现,但它没有线程的生命周期,实现它的类本身不是一个线程;v启动线程时,都应调用线程的start方法。12.4.1 继承Thread类v覆盖其run方法,其余方法继承Thread的vclass MultThread extends Thread private String id; public MultThread (String str) id = str;public

6、void run() for(int i=0; i4; i+)for(int j=0; j100000000; j+); System.out.println(id+ is running.); class Test public static void main(String args) MultThread dog = new MultThread (doggy); MultThread cat = new MultThread (kitty); dog.start(); cat.start(); v注意在上页的程序代码中,不能直接调用run方法,这样只是把run方法运行一遍而已,并没有激

7、活线程。正确的方式是调用由Thread类继承而来的start方法,然后由这个方法在计划表(scheduler)中登录这个线程,最后这个线程开始运行时,run方法自然会被调用。v不管是继承Thread创建线程,还是实现Runnable接口创建线程,都应该调用start方法启动线程;v由结果可以看出,这两个线程是一起运行的。但哪一个字符串先出现则不一定,看谁抢到CPU的资源。12.4.2 实现Runnable接口vclass RunnableThread implements Runnable private String id; public RunnableThread (String str

8、) id = str; public void run() for(int i=0; i4; i+) for(int j=0; j100000000; j+); System.out.println(id+ is running.); class Test public static void main(String args) RunnableThread dog = new RunnableThread (doggy); RunnableThread cat = new RunnableThread (kitty); Thread t1 = new Thread(dog); Thread

9、t2 = new Thread(cat); t1.start(); t2.start(); v当一个类已经继承了另一个类时,可通过实现Runnable接口创建线程;v用实现Runnable接口创建线程时,可以使多个线程共享同一资源;v用实现Runnable接口创建线程时,因为本类没有线程的生命周期,因此必须新建一个线程。12.5 Thread类vclass MultThread extends Thread private String id; public MultThread (String str) id = str; public void run()for(int i=0; i4;

10、i+)try sleep(1000); catch(InterruptedException e) e.printStackTrace(); System.out.println(id+ is running.); class Test public static void main(String args) MultThread dog = new MultThread (doggy); MultThread cat = new MultThread (kitty); dog.start(); cat.start();System.out.println(main() method fini

11、shed);sleep方法抛出了一个检查性异常,必须捕获或向上抛出yield方法vclass MultiThreadpublic static void main(String args) MyThread mt = new MyThread();mt.start();int index = 0;while(true) if(index+ = 1000) break;System.out.println(main );class MyThread extends Thread public void run() while(true) System.out.println(MyThread);

12、yield();join方法可以使线程按顺序输出这和单线程的效果一样,一般不用vpublic static void main(String args) MultThread dog = new MultThread (doggy); MultThread cat = new MultThread (kitty); dog.start(); trydog.join(); catch(InterruptedException e)e.printStackTrace(); cat.start(); trycat.join(); catch(InterruptedException e)e.prin

13、tStackTrace(); System.out.println(main() method finished); v通过多线程实现龟(Tortoise)兔(Rabbit)赛跑:赛程为1000米,兔子每100毫秒跑100米,乌龟每100毫秒跑10米,当兔子跑到900米时开始睡觉,乌龟跑到终点时,唤醒兔子。public class Tortoise implements Runnableprivate Thread r; public TortoiseB( Thread r)this.r = r;public void run( )for( int i=0; i=1000; i+=10 )Sy

14、stem.out.println( 乌龟- + (i) );tryThread.sleep( 100 );catch( Exception e )if( i = 1000 )trySystem.out.println( Tortoise is Winner! );System.out.println( Rubbit awake! );r.resume();catch( Exception e )public class Rubbit implements Runnablepublic void run()for( int i=0; i0) tryThread.sleep(10);catch (

15、InterruptedException e) e.printStackTrace();System.out.println(Thread.currentThread().getName() + sell tickets + tickets);tickets - -;class TicketsSystem public static void main(String args) SellThread st = new SellThread();Thread t1 = new Thread(st);Thread t2 = new Thread(st);Thread t3 = new Thread

16、(st);Thread t4 = new Thread(st);t1. start(); t2. start(); t3. start(); t4. start();没有同步时的情况同步方法:方法声明时加上synchronized关键字此时锁的是类的当前对象:thisvclass SellThread implements Runnable int tickets = 100;public void run() while(true) sell();public synchronized void sell() if(tickets0) tryThread.sleep(10);catch (I

17、nterruptedException e) e.printStackTrace();System.out.println(Thread.currentThread().getName() + sell tickets + tickets);tickets-;同步块,锁某一对象语法:synchronized(对象)实现语句vclass SellThread implements Runnable Object obj = new Object();int tickets = 100;public void run() while(true) synchronized (obj)if(ticke

18、ts0) tryThread.sleep(10); catch (InterruptedException e) e.printStackTrace();System.out.println(Thread.currentThread().getName() + sell tickets + tickets);tickets-;wait()和notify()vwait()方法和notify()方法都是Object类中的方法,用对象来调用;v当调用某对象的wait()方法时,当前线程进入该对象的等待队列中;v当调用某对象的notify()方法时,唤醒该对象等待队列中的某个线程。v这两个方法的调用通

19、常放在同步方法或同步块中要求实现Runnable接口,编程实现测试打字速度的GUI界面的应用程序import java.awt.*;import java.awt.event.*;public class TextTest extends Frame implements Runnable,ActionListenerPanel p1,p2;Label testLabel,timeLabel,scoreLabel;TextArea ta;Button startButton;int i = 10;public TextTest()p1 = new Panel();p2 = new Panel(

20、);p1.setLayout(new GridLayout(2,1);p2.setLayout(new GridLayout(2,1);testLabel = new Label(测字软件,Label.CENTER);timeLabel = new Label(剩余时间: +10+ 秒);scoreLabel = new Label(成绩: ? 字/分);startButton = new Button(开始);ta = new TextArea(30,50);ta.setEditable(false);p1.add(testLabel);p1.add(timeLabel);p2.add(sc

21、oreLabel);p2.add(startButton);add(p1,BorderLayout.NORTH);add(ta);add(p2,BorderLayout.SOUTH);setTitle(测字软件);setSize(300,400);setVisible(true);startButton.addActionListener(this);addWindowListener(new WindowAdapter()public void windowClosing(WindowEvent e)System.exit(0););public void actionPerformed(A

22、ctionEvent e)ta.setText();ta.setEditable(true);ta.requestFocus();Thread x = new Thread(TextTest.this);x.start();public void run()for(i = 10; i0;i-)timeLabel.setText(剩余时间: +i+ 秒);startButton.removeActionListener(this);tryThread.sleep(1000);catch(InterruptedException e)e.printStackTrace();ta.setEditable(false);scoreLabel.setText(成绩: +ta.getText().length()*6+ 字/分);startButton.addActionListener(this);public static void main(String args)new TextTest();

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 医学/心理学 > 基础医学

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号