java中二种方法实现一个线程

本文介绍了在Java中创建线程的两种主要方法:通过继承Thread类和实现Runnable接口。通过具体的代码示例展示了如何使用这两种方法来启动和执行线程,并解释了线程的基本操作,如休眠和中断处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有两种方法,一种是继承Thread类,另一种是实现Runable接口
(1)
public class Test{
 public static void main(String [] args){
  MyThread mt=new MyThread();
  mt.start();
  }
}
class MyThread extends Thread{//继承Thread类
  int count=0;
  public void run(){//重写run()方法
  while(true){
  System.out.println("MyThread is running !"+count+"times");
  try{
  sleep(1000);//每隔1m输出
  count++;
  }catch(InterruptedException e){//扑捉可能产生的中断异常(非运行时异常)
  System.out.println("产生中断异常");
  }
if(count==10)return;
  }
  }

(2)  
public class Test{
 public static void main(String [] args){
  RunableDemo rd=new RunableDemo();
  Thread t=new Thread(rd);
  t.start();
  }
}
 class RunableDemo implements Runable{//实现Runable接口
  int count=0;
  public void run(){//重写run()方法
  while(true){
  System.out.println("MyThread is running !"+count+"times");
  try{
  Thread.sleep(1000);//静态方法,可以用类名直接调用
  count++;
  }catch(InterruptedException e){//扑捉可能产生的中断异常
  System.out.println("产生中断异常");
  }
  if(count==10)return;
  }
  }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值