Thread

本文详细介绍了在Java中使用多线程的两种常见方法:通过实现Runnable接口和继承Thread类来创建线程。通过具体代码示例,展示了如何定义线程任务,创建线程对象,并启动线程执行。

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

二、启用多线程
1)通过Runnable接口创建线程
a.定义一个“任务类”并是实现Runnable接口,覆写Runnable接口run()方法 【run()方法中定义具体的任务代码或处理逻辑】;
b.定义“任务类”后,创建“任务类”对象;
c.任务必须在线程中执行,创建Thread类对象,将实现Runnable接口的任务类作为参数传递给Thread类对象;
d.调用Thread类对象的start()方法,启动一个线程【run()方法执行,结束则线程终止】。

package com.muzeet.mutithread;
2 
3 //每个任务都是Runable接口的一个实例,任务是可运行对象,线程是便于任务执行的对象。必须创建任务类,重写run方法定义任务
4 public class ThreadDemo1 implements Runnable {
5     private int countDown = 10;
6     @Override
7     //重写run方法,定义任务
8     public void run() {
9         while(countDown-- >0)
10         {
11             System.out.println("$" + Thread.currentThread().getName() 
12                     + "(" + countDown + ")");
13         }
14     }
15     //调用start方法会启动一个线程,导致任务中的run方法被调用,run方法执行完毕则线程终止
16     
17     public static void main(String[] args) {
18         Runnable demo1 = new ThreadDemo1();
19         
20         Thread thread1 = new Thread(demo1);
21         Thread thread2 = new Thread(demo1);
22         thread1.start();
23         thread2.start();
24         
25         System.out.println("火箭发射倒计时:");
26         
27         
28     }
29 
30 }
   

2)继承Thread类创建线程
a.创建一个“任务类”继承Thread类【Thread类实现了Runnable接口】,并重写run()方法;
b.创建“任务类”对象;
c.调用start()方法。

package com.muzeet.mutithread;
2 
3 //每个任务都是Runable接口的一个实例,任务是可运行对象,线程即可运行对象。必须创建任务类,重写run方法定义任务
4 public class ExtendFromThread extends Thread {
5     private int countDown = 10;
6     @Override
7     //重写run方法,定义任务
8     public void run() {
9         while(countDown-- >0)
10         {
11             System.out.println("$" + this.getName() 
12                     + "(" + countDown + ")");
13         }
14     }
15     //调用start方法会启动一个线程,导致任务中的run方法被调用,run方法执行完毕则线程终止
16     
17     public static void main(String[] args) {
18         
19         ExtendFromThread thread1 = new ExtendFromThread();
20         ExtendFromThread thread2 = new ExtendFromThread();
21         thread1.start();
22         thread2.start();
23         
24         System.out.println("火箭发射倒计时:");
25         
26         
27     }
28 
29 }
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值