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