多线程 ·多线程 在Java中,一个应用程序可以包含多个线程。 每个线程执行特定的任务,并可与其他线程并 发执行 多线程使系统的空转时间最少,提高cPU利用 率 多线程编程环境用方便的模型隐藏cPU在任务 问切换的事实 6 北大青鸟
6 多线程 • 多线程 – 在Java中,一个应用程序可以包含多个线程。 每个线程执行特定的任务,并可与其他线程并 发执行 – 多线程使系统的空转时间最少,提高CPU利用 率 – 多线程编程环境用方便的模型隐藏CPU在任务 间切换的事实
主线程 在Java程序启动时,一个线程立刻运行 该线程通常称为程序的主线程。 主线程的重要性体现在两个方面: 它是产生其他子线程的线程。 通常它必须最后完成执行,因为它执行各种 关闭动作。 北大青鸟
7 主线程 • 在Java程序启动时,一个线程立刻运行, 该线程通常称为程序的主线程。 • 主线程的重要性体现在两个方面: – 它是产生其他子线程的线程。 – 通常它必须最后完成执行,因为它执行各种 关闭动作
主线程示例 class Mythread extends Thread i public static void main( String args y获得当线程, Thread t= Thread currentThread ()i 即主线程 System. out. print1n("当前线程是:"+t) t setName("My Java Thread"); 改变线程的 内部名称 System. out. println("当前线程名是:"+t); try for(int主=0;<3;+十) System. out. println (i)i Thread. sleep(1500)i 输 回命令提示符 c:、ava> java Mythread Thread [main.5. main] 名是: Thread[MyJavaThread,5,nain] catch(InterruptedExcept: 5 System.out. println("* 北大青鸟
8 主线程示例 class Mythread extends Thread { 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;i<3;i++) { System.out.println(i); Thread.sleep(1500); } } catch(InterruptedException e) { System.out.println("主线程被中断"); } } } 获得当前线程, 即主线程 改变线程的 内部名称 输出每个数后 暂停1500毫 秒
创建线程21 ·通过以下两种方法创建 Thread对象 声明一个 Thread类的子类,并覆盖run0方法。 class mythread extends Thread i pub1 ic void run(){/覆盖该方法*/} 声明一个实现 Runnable接口的类,并实现run0 方法。 class mythread implements Runnable public void run(){/实现该方法*/ 北大青鸟
9 创建线程 2-1 • 通过以下两种方法创建Thread 对象: - 声明一个 Thread 类的子类,并覆盖 run() 方法。 class mythread extends Thread { public void run( ) {/* 覆盖该方法*/ } } - 声明一个实现 Runnable 接口的类,并实现 run() 方法。 class mythread implements Runnable{ public void run( ) {/* 实现该方法*/ } }
创建线程22 要触发一个新线程,使用star方法,如 Mythread t new Mythread)i 七. start(); ·在调用 start(方法时,将刨建一个新的控 制线程,接着它将调用run方法。 ·run(方法中的代码定义执行线程所需的功 能。 北大青鸟
10 创建线程 2-2 • 要触发一个新线程,使用 start() 方法,如: Mythread t = new Mythread(); t.start(); • 在调用 start() 方法时,将创建一个新的控 制线程,接着它将调用run() 方法。 • run() 方法中的代码定义执行线程所需的功 能