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

时间:2020-11-27 17:35:16

 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();
			}			
		}

	}
}

通过如下方式运行:

1     public static void main(String[] args) {
2         
3         MyThread mThread1 = new MyThread("线程一");
4         MyThread mThread2 = new MyThread("线程二");
5         MyThread mThread3 = new MyThread("线程三");
6         mThread1.start();
7         mThread2.start();
8         mThread3.start();
9     }    

运行结果如下:

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

 

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

多线程类:

 1 class RunThread implements Runnable{
 2 
 3     int Counter = 0;
 4     @Override
 5     public synchronized void run() {
 6         for(int i=0;i<5;i++){
 7             System.out.println(Thread.currentThread().getName()+"count:"+Counter++);
 8             try {
 9                 Thread.sleep(100);
10             } catch (InterruptedException e) {
11                 // TODO Auto-generated catch block
12                 e.printStackTrace();
13             }            
14         }
15     }    
16 }

实现方式:

 1     public static void main(String[] args) {
 2         
 3         RunThread rThread = new RunThread();
 4         Thread t1 = new Thread(rThread,"线程一");
 5         Thread t2 = new Thread(rThread,"线程二");
 6         Thread t3 = new Thread(rThread,"线程三");
 7         t1.start();
 8         t2.start();
 9         t3.start();
10   }

输出结果:

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

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

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