Java多线程

1.Java提供浏览两种创建线程方法:
通过实现Runable接口;
通过继承Thread类本身。
2.通过实现Runnable接口来创建线程
创建一个线程,最简单的方法是创建一个实现Runnable接口的类。

实现Runnable,一个类只需要执行一个方法调用run(),声明如下:
public void run()
你可以重写该方法,重要的是理解的run()可以调用其他方法,使用其他类,并声明变量,就像主线程一样。

在创建一个实现Runnable接口的类之后,你可以在类中实例化一个线程对象

定义构造方法,下面的这个是我们经常使用的:
Thread(Runnable threadob,String threadName)

创建新线程之后,你调用它的start()方法运行。
void start()

  1. 实例
    开始执行实例:
   // 创建一个新的线程
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // 创建第二个新线程
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + 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("Child interrupted.");
       }
           System.out.println("Exiting child thread.");
      }
}
 
public class ThreadDemo {
      public static void main(String args[]) {
           new NewThread(); // 创建一个新线程
           try {
                  for(int i = 5; i > 0; i--) {
                  System.out.println("Main Thread: " + i);
                  Thread.sleep(100);
               }
         } catch (InterruptedException e) {
           System.out.println("Main thread interrupted.");
       }
           System.out.println("Main thread exiting.");
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值