java中线程的创建-初学

java中创建线程有两种方式一是继承Thread线程类二是实现Runnable接口。


继承Thread线程类

继承类必须重写run()方法,这是新线程的入口点。它也必须调用start()方法才能执行。

实例

// 通过继承 Thread 创建线程
class MyThread extends Thread {
   MyThread() { //构造函数
      System.out.println("孩子线程运行.");
      start(); // 开始线程
   }
 
   // 线程入口
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("孩子线程: " + i);
                            // 让线程休眠一会
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("孩子线程中断.");
      }
      System.out.println("退出孩子线程.");
   }
}
 
public class Test {
   public static void main(String args[]) {
      new MyThread(); // 创建一个新线程
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("主线程: " + i);
            Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("主线程中断.");
      }
      System.out.println("主线程退出.");
   }
}
实现Runnable接口

通过实现Runnable接口来创建线程是最简单的一种方式

为了实现Runnable,一个类只需要重写一个方法调用run()
// 创建一个新的线程
class MyThread implements Runnable {
   Thread t;
   MyThread() {
      // 创建新线程
      t = new Thread(this, "Demo Thread");
      System.out.println("孩子线程的名字: " + t);
      t.start(); // 开始线程
   }
  
   //线程入口
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            //休眠
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("孩子线程中断.");
     }
     System.out.println("孩子线程结束.");
   }
}
 
public class Test {
   public static void main(String args[]) {
      new MyThread(); // 创建一个新线程
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("主线程: " + i);
           Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("主线程中断.");
      }
      System.out.println("主线程结束.");
   }
}
优缺点比较
采用继承Thread类方式:
(1)优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
(2)缺点:因为线程类已经继承了Thread类,所以不能再继承其他的父类。
采用实现Runnable接口方式:
(1)优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标(target)对象,所以非常适合多个相同线程来处理同一份资源的情况。
(2)缺点:编程稍微复杂,如果需要访问当前线程,必须使用Thread.currentThread()方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值