Java通过继承thread类与实现Runnable接口实现多线程的区别

Java中线程的创建有两种方式:

1.  通过继承Thread类,重写Thread的run()方法,将线程运行的逻辑放在其中

2.  通过实现Runnable接口,实例化Thread类

一、通过继承Thread类实现多线程

class MyThread extends Thread{
String name = null;
int ticket = 0;
public MyThread(String name){
this.name = name;
}
public synchronized void run(){
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+this.name+" ticket:"+ticket++);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
}

通过如下方式运行:

     public static void main(String[] args) {

         MyThread mThread1 = new MyThread("线程一");
MyThread mThread2 = new MyThread("线程二");
MyThread mThread3 = new MyThread("线程三");
mThread1.start();
mThread2.start();
mThread3.start();
}

运行结果如下:

 Thread-1线程二 ticket:0
Thread-0线程一 ticket:0
Thread-2线程三 ticket:0
Thread-1线程二 ticket:1
Thread-0线程一 ticket:1
Thread-2线程三 ticket:1
Thread-1线程二 ticket:2
Thread-2线程三 ticket:2
Thread-0线程一 ticket:2
Thread-1线程二 ticket:3
Thread-2线程三 ticket:3
Thread-0线程一 ticket:3
Thread-1线程二 ticket:4
Thread-2线程三 ticket:4
Thread-0线程一 ticket:4

二、通过继承Runnable接口实现多线程

多线程类:

 class RunThread implements Runnable{

     int Counter = 0;
@Override
public synchronized void run() {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"count:"+Counter++);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

实现方式:

     public static void main(String[] args) {

         RunThread rThread = new RunThread();
Thread t1 = new Thread(rThread,"线程一");
Thread t2 = new Thread(rThread,"线程二");
Thread t3 = new Thread(rThread,"线程三");
t1.start();
t2.start();
t3.start();
  }

输出结果:

 线程一count:0
线程一count:1
线程一count:2
线程一count:3
线程一count:4
线程二count:5
线程二count:6
线程二count:7
线程二count:8
线程二count:9
线程三count:10
线程三count:11
线程三count:12
线程三count:13
线程三count:14

Java通过继承thread类与实现Runnable接口实现多线程的区别

Java通过继承thread类与实现Runnable接口实现多线程的区别

  

上一篇:Spring的事务管理基础知识


下一篇:将图片base64格式转换为file对象并读取(两种方式读取)