Java多线程-创建多线程:继承Thread类&实现Runnable接口
继承Thread类,创建多线程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | MyThread. class package com.test.interview; public class MyThread extends Thread { private String name; public MyThread(String name) { this .name = name; } @Override public void run() { for ( int i = 0 ; i < 10 ; i++) { System.out.println( "thread start:" + this .name + ",i=" + i); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | ThreadDemo. class package com.test.interview; public class ThreadDemo { public static void main(String[] args) { MyThread mt = new MyThread( "thread1" ); MyThread mt2 = new MyThread( "thread2" ); MyThread mt3 = new MyThread( "thread3" ); mt.start(); mt2.start(); mt3.start(); } } |
实现Runnable接口,创建多线程:*(推荐这种方式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | RunnableDemo. class package com.test.interview; public class RunnableDemo { public static void main(String[] args) { MyRunnable mr1 = new MyRunnable( "Runnable1" ); MyRunnable mr2 = new MyRunnable( "Runnable2" ); MyRunnable mr3 = new MyRunnable( "Runnable3" ); Thread t1 = new Thread(mr1); Thread t2 = new Thread(mr2); Thread t3 = new Thread(mr3); t1.start(); t2.start(); t3.start(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | MyRunnable. class package com.test.interview; public class MyRunnable implements Runnable { private String name; public MyRunnable(String name) { this .name = name; } @Override public void run() { for ( int i = 0 ; i < 10 ; i++) { System.out.println( "thread start:" + this .name + ",i=" + i); } } } |
Thread&Runnable的关系:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤