JAVA语言面向对象程序设计 教学课件 作者 马俊 8JAVA.ppt
文本预览下载声明
Essential Programming with Java / chapter 11 线程 第八章 目标 了解多线程的概念 掌握如何创建线程 了解死锁的概念 掌握线程同步 掌握使用 wait() 和 notify() 在线程之间进行通信 多任务处理 基于线程的多任务处理的优点 多线程 主线程 主线程示例 class Mythread { public static void main(String args[]) { Thread t= Thread.currentThread(); System.out.println(当前线程是: +t); t.setName(MyJavaThread); System.out.println(当前线程名是: +t); try { for(int i=0;i3;i++) { System.out.println(i); Thread.sleep(1500); } } catch(InterruptedException e) { System.out.println(主线程被中断); } } } 创建线程 2-1 创建线程 2-2 创建线程示例 class MyThread1 extends Thread { public static void main(String args[]) { Thread t= Thread.currentThread(); System.out.println(主线程是: +t); MyThread1 ex = new MyThread1(); ex.start(); } public void run() { System.out.println(子线程是:+this); } } 线程的状态 4-1 新建 (Born) : 新建的线程处于新建状态 就绪 (Ready) : 在创建线程后,它将处于就绪状态, start() 方法被调用 运行 (Running) : 线程在开始执行时进入运行状态 睡眠 (Sleeping) : 线程的执行可通过使用 sleep() 方法来暂时中止。在睡眠后,线程将进入就绪状态 线程的状态4-2 线程状态4-3 线程的状态 4-4 可能使线程暂停执行的条件 线程状态的示例 class ThreadStateDemo extends Thread { Thread t; public ThreadStateDemo() { t=new Thread(this); System.out.println (线程 t 为新建!); System.out.println (线程 t 为就绪!); t.start(); } public void run() { try { System.out.println (线程 t 在运行!); t.sleep(500); System.out.println(线程 t 在短时间睡眠后重新运行!); } catch (InterruptedException IE) { System.out.println(线程被中断); } } Thread 类中的重要方法 2-1 Thread 类中的重要方法 2-2 线程优先级 线程同步 如何在 Java 中获得同步 同步基于“监视器”这一概念。“监视器”是用作互斥锁的对象。在给定时刻,只有一个线程可以拥有监视器。 Java中所有的对象都拥有自己的监视器 两种方式实现同步: 使用同步方法 synchronized void methodA() { } 使用同步块 synchronized(object) { //要同步的语句 } 同步方法 class One { synchronized void display(int num) { System.out.print(+num); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println(中断); } System.out.println( 完成); } } 同步块 class One { void display(int num) { Syst
显示全部