java中关于线程的创建有三种: (1)通过继承Thread类创建线程.

              (2)通过实现Runnable接口创建线程.

              (3)通过Callable 和 Future 接口创建线程.

* * * * * * * * * * * * * * * * * * * * * * * * * 继承Thread类创建线程 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

  1)重写run()方法, 该方法的方法体是线程需要执行的任务;

  2)启动线程, 调用start();

代码 :

 1 package demo;
2
3 public class TestThread{
4
5 public static void main(String[] args) {
6 Thread thread = new MyThread();
7 thread.start();
8 }
9 }
10
11 class MyThread extends Thread{
12
13 public void run() {
14 try {
15 System.out.println("稍等下!");
16 sleep(5000);
17 System.out.println(getName()+"执行了!");
18 } catch (InterruptedException e) {
19 e.printStackTrace();
20 }
21 }
22 }

* * * * * * * * * * * * * * * * * * * * * * * * * 实现Runnable接口创建线程 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

  1. 覆盖接口中run()方法, 该方法的方法体是线程需要执行的任务;

  2. 通过实现Thread类的构造函数Thread(Runnable target)或Thread(Runnable target, String name)来创建Thread实例, 这样就创建一个完整的线程对象;

  3. 启动线程, 调用start();

 代码 :

 1 package demo;
2
3 public class TestRunnable{
4
5 public static void main(String[] args) {
6 Thread thread=new Thread(new MyThread2());
7 Thread thread1=new Thread(new MyThread2());
8 thread.start();
9 thread1.start();
10 }
11 }
12
13 class MyThread2 implements Runnable{
14
15 public void run() {
16 try {
17 System.out.println("稍等下!");
18 Thread.sleep(500);
19 for(int i=0;i<100;i++){
20 System.out.println(Thread.currentThread().getName()+"线程的"+i+"执行了!");
21 }
22 } catch (InterruptedException e) {
23 e.printStackTrace();
24 }
25 }
26 }

* * * * * * * * * * * * * * * * * * * * * * * 实现Callable接口与Future接口创建线程 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

继承与实现接口的区别

  1. 将线程的任务从线程的子类中分离出来, 进行单独的封装, 按照面向对象的思想将任务封装为对象.

  2. 避免java单继承的局限性.

最新文章

  1. arm 2440 linux 应用程序 nes 红白机模拟器 第2篇 InfoNES
  2. C#开源系统大汇总
  3. H5测试区别与PC端测试关注点
  4. 文件快速搜索工具-Everything的使用(转)
  5. 越狱后想禁用Spotlight
  6. Xamarin.Android开发实践(六)
  7. cocos2dx从入门到精通课程
  8. 创业草堂之一:创业的Idea是怎样产生的?
  9. [Gauss]POJ1753 Flip Game
  10. 利用WebRequest类上传文件
  11. 转:Linux基本命令大全
  12. 常用PHP函数整理
  13. DML、DDL、DCL的区别
  14. maven &quot;mvn不是内部或外部命令,也不是可运行的程序或批处理文件&quot;
  15. The value for the useBean class attribute xxx is invalid
  16. [IDEA_3] IDEA 配置 GitHub 并上传项目
  17. LeetCode Letter Combinations of a Phone Number (DFS)
  18. LayUI——数据表格使用
  19. Flask 学习(四)静态文件
  20. Redmine 邮件配置

热门文章

  1. addrinfo结构体原型-(转自 cxz2009)
  2. Java,用户刷屏检测\相似字符串检测
  3. jupyter notebook快捷键使用的注意点
  4. TorchScript神经网络集成技术
  5. NVIDIA A100 GPUs上硬件JPEG解码器和NVIDIA nvJPEG库
  6. AMD Ryzen 5000‘Cezanne’APU
  7. CArray CList CMap 插入与遍历效率对比
  8. 汉枫Wi-Fi串口服务器HF2211S应用案例
  9. 『言善信』Fiddler工具 — 14、使用Fiddler进行弱网测试
  10. 在Centos7下安装RabbitMQ