线程的操作 继承 thread 和实现renable 接口

本文介绍了使用Java创建线程的两种方法:一种是通过继承Thread类并重写run方法,另一种是实现Runnable接口并在Thread类中指定此Runnable对象。同时展示了如何启动线程和在运行过程中让线程暂停。

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



线程的操作 继承 thread 和实现renable 接口


//线程的各个方法
t.isAlive();
//是否存活
t.resume();
//强制关闭
package xiancheng;
//继承thread 实现线程
public class Student extends Thread{
 public void run(){
  this.getName();
  
  for (int i = 0; i <50; i++) {
   try {
                                //线程迟钝300毫秒
    Thread.currentThread().sleep(300);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(this.getName()+(i+1));
  }
  
 }


}



//实现runnable接口来实现线程

package xiancheng;
public class Teacher implements Runnable {

 public void run(){
  for (int i = 0; i <50; i++) {
   try {
    Thread.currentThread().sleep(300);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName()+(i+1));
   
  }
  
 }
  

}


//测试类
package xiancheng;
public class Main {
 public static void main(String[] args) {
  Student st=new Student();
  st.setName("明明");
  st.start();
  Thread.currentThread().setName("main");
  Runnable rn=new Teacher();
  Thread tr=new Thread(rn);
  tr.setName("介个老师");
  tr.start();
  
 for (int i = 0; i < 50; i++) {
  try {
   Thread.currentThread().sleep(300);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
   System.out.println(Thread.currentThread().getName()+(i+1));
   
  }
 }

}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值