---
title: "Java中实现多线程有两种方式"
author: "dir_murong"
date: "2010-10-28T11:07:44Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-10-28T17:57:34Z"
id: 796292
url: "https://dir-murong.iteye.com/blog/796292"
---

众所周知，在JAVA中实现多线程有两种方式：

一种是<span style="color:red">继承于Thread类</span>

一种是<span style="color:red">实现Runnable接口</span>

本质相同的实现机制，之所以有两种实现方式，一方面针对不同爱好的用户群体，另外可能是因为JAVA不支持多继承，一旦你的类已经继承一个父类就无法再继承Thread类了，这个时候只有实现Runnable接口。

示例代码如下：

继承

public class MyThread extends Thread{
 private String thrName;
 public MyThread(String name){
  this.thrName = name;
 }
 public void run(){
  try {
   Thread.currentThread().sleep(50);
   System.out.println(this.thrName+" start");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
}

实现接口

public class MyThreadRunnable implements Runnable {

 private String thrName;
 public MyThreadRunnable(String name){
  this.thrName = name;
 }
 public void run() {
  // TODO Auto-generated method stub
  try {
   Thread.currentThread().sleep(25);
   System.out.println(this.thrName+" start");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

}