多线程流程

本文介绍了一个Java多线程的示例程序,通过创建两个线程并启动其中一个线程来展示多线程的基本用法。主线程会休眠三秒后退出,而另一个线程则会循环五次,每次休眠一秒并打印当前线程名称。

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


/**
 *<br>方法说明:构造器。实际线程,并启动这个线程。
 *<br>输入参数:
 *<br>返回类型:
 */
 twothread() {
   //获取当前的线程
   Thread t1 =Thread.currentThread();
   t1.setName("The first main thread");
   System.out.println("The running thread:" + t1.getName());
   //通过将本类(Runnable接口)和名称构造一个线程
   Thread t2 = new Thread(this,"the second thread");
   System.out.println("creat another thread"+"\t"+t2.getName());
   //启动线程
   t2.start();
   try {
     System.out.println("this thread will sleep"+"\t"+Thread.currentThread().getName());
     Thread.sleep(3000);
   }catch (InterruptedException e) {
     System.out.println("first thread has wrong");
   }
   System.out.println("first thread exit");
 }
/**
 *<br>方法说明:线程主体。实现run方法。
 *<br>输入参数:
 *<br>返回类型:
 */
 public void run() {
   try {
     for (int i=0;i<5;i++) {
       System.out.println("Sleep time for thread :"+Thread.currentThread().getName());
       Thread.sleep(1000);
     }
  } catch (InterruptedException e) {
    System.out.println("thread has wrong");
  }
  System.out.println("second thread exit");
 }
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
 public static void main(String args[]) {
   new twothread();
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值