1、通过继承Thread类的方式创建多线程(这里只是简单的代码演示创建多线程的方法)
1 package com.baozi.exer; 2
3 public class ThreadDemo { 4 public static void main(String[] args) { 5 Thread1 t1=new Thread1(); 6 Thread2 t2=new Thread2(); 7 t2.start(); 8 t1.start(); 9 } 10 } 11 class Thread1 extends Thread { 12 @Override 13 public void run() { 14 for (int i = 0; i <= 100; i++) { 15 if (i % 2 == 0) { 16 System.out.println(Thread.currentThread().getName() + " : " + i); 17 } 18 } 19 } 20 } 21 class Thread2 extends Thread { 22 @Override 23 public void run() { 24 for (int i = 0; i <= 100; i++) { 25 if (i % 2 != 0) { 26 System.out.println(Thread.currentThread().getName() + " : " + i); 27 } 28 } 29 } 30 }
2、通过实现Runnable接口的方式创建多线程
1 package com.baozi.test; 2 3 public class ThreadRunnable { 4 public static void main(String[] args) { 5 MyThread1 mt1 = new MyThread1(); 6 Thread t1 = new Thread(mt1); 7 t1.start(); 8 } 9 } 10 class MyThread1 implements Runnable { 11 @Override 12 public void run() { 13 for (int i = 0; i < 100; i++) { 14 if (i % 2 == 0) { 15 System.out.println(Thread.currentThread().getName() + " : " + i); 16 } 17 } 18 } 19 }
3、两种方式的比较:
- 实现Runnable接口的方式没有类的单继承性的限制性;
- 实现的方式更适合处理多个线程之间有共享数据的情况;
所以在开发中会优先选择实现Runnable接口的方式实现多线程