当前位置: 首页> 财经> 创投人物 > 济南建设管理局官网_水果套餐网站_软文代写发布_百度竞价什么意思

济南建设管理局官网_水果套餐网站_软文代写发布_百度竞价什么意思

时间:2025/7/10 7:24:07来源:https://blog.csdn.net/2301_79184547/article/details/142832767 浏览次数:0次
济南建设管理局官网_水果套餐网站_软文代写发布_百度竞价什么意思

1.创建线程

方法1:继承Thread类

public class Demo1 {public static void main(String[] args) {MyThread myThread = new MyThread();myThread.start();while (true) {System.out.println("main");}}}class MyThread extends Thread {public void run() {while (true) {System.out.println("MyThread");}}
}

方法2.使用匿名内部类

    public static void main(String[] args) {Thread thread = new Thread() {public void run() {while (true) {System.out.println("Thread");                      }}};thread.start();while (true) {System.out.println("main");}}

 方法3.使用lambda表达式

    public static void main(String[] args) {Thread thread = new Thread(() -> {while (true) {System.out.println("Thread");}});thread.start();while (true) {System.out.println("mian");}}

注意,在使用lambda表达式时,若要使用外面的变量(main中的局部变量但不在lambda中的变量),则该变量不能被修改,因为使用时会触发变量捕获,由于lambda是回调函数,执行时机是很久之后(操作系统真正创建出线程后才会执行),有可能main先执行完,导致该变量在使用前就被销毁,于是该变量不能被修改。

若该变量为引用类型,则这个引用一旦指向一个对象后,就不能指向其他对象,但指向的对象本体的属性和方法能被修改。

在上述代码中,都使用了Thread来创建线程thread,再使用start()方法来启动线程,虽然thread.run()也能使程序运行,但本质上并没有创建出一个新的线程,只是普通的方法调用。

2.线程中断(终止)

使用thread.interrupt()方法可使thread线程终止运行,但该方法还会唤醒阻塞方法(如sleep),唤醒后可能会报错。

也可以直接在run方法中直接return,从而使该线程终止运行。

isInterruptrd()可以判断线程是否终止,若终止返回true。

3.线程休眠

使用sleep()方法可使当前线程自动放弃CPU资源从而使该线程停止运行,休眠时间为毫秒,使用该方法时要处理异常。

4.获取线程实例

当我们使用匿名内部类和lambda表达式时,由于thread线程还未创建,这这时要在run()方法中使用该线程的实例时,就要调用Thread.currentThread()方法来获取该线程的引用,该方法为静态方法。

关键字:济南建设管理局官网_水果套餐网站_软文代写发布_百度竞价什么意思

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: