小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java 多线程编程

发布者: 小白教程



实例

  1. // 通过继承 Thread 创建线程
  2. class NewThread extends Thread {
  3.    NewThread() {
  4.       // 创建第二个新线程
  5.       super("Demo Thread");
  6.       System.out.println("Child thread: " + this);
  7.       start(); // 开始线程
  8.    }
  9.  
  10.    // 第二个线程入口
  11.    public void run() {
  12.       try {
  13.          for(int i = 5; i > 0; i--) {
  14.             System.out.println("Child Thread: " + i);
  15.                             // 让线程休眠一会
  16.             Thread.sleep(50);
  17.          }
  18.       } catch (InterruptedException e) {
  19.          System.out.println("Child interrupted.");
  20.       }
  21.       System.out.println("Exiting child thread.");
  22.    }
  23. }
  24.  
  25. public class ExtendThread {
  26.    public static void main(String args[]) {
  27.       new NewThread(); // 创建一个新线程
  28.       try {
  29.          for(int i = 5; i > 0; i--) {
  30.             System.out.println("Main Thread: " + i);
  31.             Thread.sleep(100);
  32.          }
  33.       } catch (InterruptedException e) {
  34.          System.out.println("Main thread interrupted.");
  35.       }
  36.       System.out.println("Main thread exiting.");
  37.    }
  38. }

编译以上程序运行结果如下:

  1. Child thread: Thread[Demo Thread,5,main]
  2. Main Thread: 5
  3. Child Thread: 5
  4. Child Thread: 4
  5. Main Thread: 4
  6. Child Thread: 3
  7. Child Thread: 2
  8. Main Thread: 3
  9. Child Thread: 1
  10. Exiting child thread.
  11. Main Thread: 2
  12. Main Thread: 1
  13. Main thread exiting.

Thread 方法

下表列出了Thread类的一些重要方法:

序号方法描述
1public void start()
使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
2public void run()
如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。
3public final void setName(String name)
改变线程名称,使之与参数 name 相同。
4public final void setPriority(int priority)
 更改线程的优先级。
5public final void setDaemon(boolean on)
将该线程标记为守护线程或用户线程。
6public final void join(long millisec)
等待该线程终止的时间最长为 millis 毫秒。
7public void interrupt()
中断线程。
8public final boolean isAlive()
测试线程是否处于活动状态。

测试线程是否处于活动状态。 上述方法是被Thread对象调用的。下面的方法是Thread类的静态方法。

序号方法描述
1public static void yield()
暂停当前正在执行的线程对象,并执行其他线程。
2public static void sleep(long millisec)
在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
3public static boolean holdsLock(Object x)
当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true。
4public static Thread currentThread()
返回对当前正在执行的线程对象的引用。
5public static void dumpStack()
将当前线程的堆栈跟踪打印至标准错误流。

上一篇:Java 发送邮件下一篇:Java Applet基础

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:31 , Processed in 0.021934 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部