线程的创建和启动

一般有三种方法

1、通过继承Thread类来创建。

首先重写该类的run方法(线程执行体),创建Thread子类的实例,即线程对象,调用start()方法启动线程,如果没有start的话不会启动多个线程。常用方法:Thread.currentThread()和getName()(两者一起或者只用后者都可以),当然也可以自己通过setName(String name)来设置线程的启动名字

2、实现Runnable接口

首先同样是重写run方法,创建Runnable实现类的实例(假如是st),并以此实例作为Thread的target来创建Thread对象(new(st)或者new(st,“线程自定义名字”)),该Thread才是真正的线程对象。最后调用start方法启动(new Thread(st).start());(只能用Thread.currentThread.getName()不能直接用getName());不要忘了线程的数量应包括main方法所在的主线程。

总结:继承Thread类的方法创建线程类的时候,多个线程不能共享线程类的实例变量,而实现Runnable接口可以,因为其只是作为target传入Thread,多个线程共享一个target,那么线程的实例属性的变化是连续的。(验证的时候注意,这里说的线程不包括主线程执行的结果是连续的,只是start启动的线程的实例变量变化连续(不是局部变量))

3、通过实现Callable接口和Future来创建线程

步骤:A、创建Callable接口的实现类,并实现call()方法(跟run方法作用一样,只不过call方法可以有返回值和抛出异常)

B、创建实现Callable的类的实例,使用FutureTask来包装Callable对象(),FutureTask也就封装了call()方法的返回值

C、使用FutureTask对象作为Thread对象的target来创建并启动线程

D、使用FutureTask对象的get()方法可以获得子线程结束后的返回值。

public test implements Callable<Integer>

. .public Integer call(){

. .int i=0;

. .for(;i<100;i++){

. . System.out.println(Thread.currentThread().getName()+“的i值是”+i);

. .}

return i;

. .

. .}public static void main(String[]args){

. . test rt=new test();

. .FutureTask<Integer> task=new FutureTask<Integer>(rt);

. .for(int i=0;i<100;i++){

. .Syste....println(Thread.currentThread.getName());

. .if(i==20) new Thread(task,"有返回值的线程").start();

. .try{System...println("子线程返回值是"+task.get())}catch(Exception e){e.print...};

. .

. .}

. .}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中可以通过`threading`模块来启动和停止线程。具体的方法如下: 启动线程: 1. 定义一个线程类,继承自`threading.Thread`类,重写`run()`方法,在`run()`方法中写入线程要执行的代码。 2. 创建线程实例对象,并调用`start()`方法启动线程,此时线程自动调用`run()`方法执行。 示例代码: ```python import threading # 自定义线程类 class MyThread(threading.Thread): def run(self): # 线程要执行的代码 print("Thread started") # 创建线程实例对象 t = MyThread() # 启动线程 t.start() ``` 停止线程: 1. 在线程中定义一个变量作为标志位,用于控制线程的运行状态。 2. 在线程中使用循环语句,根据标志位的状态来决定是否退出循环,从而终止线程的运行。 示例代码: ```python import threading import time # 自定义线程类 class MyThread(threading.Thread): def __init__(self): super().__init__() self.flag = True def run(self): # 线程要执行的代码 while self.flag: print("Thread is running...") time.sleep(1) print("Thread stopped") def stop(self): self.flag = False # 创建线程实例对象 t = MyThread() # 启动线程 t.start() # 停止线程 t.stop() ``` 注意:线程的停止并不能直接调用`stop()`方法来实现,因为这样导致线程的资源没有被释放,从而引发各种问题。正确的做法是在线程中定义一个标志位,通过修改标志位的状态来控制线程的运行状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值