package Multithreading; public class MyRunnableDemo { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); Thread thread2 = new Thread(myRunnable); thread.start(); thread2.start(); } }
package Multithreading; public class MyRunnable implements Runnable { @Override public void run() { for (int i=0; i<100;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } } }
多线程的实现方案有两种
1.继承Thread类
2.实现Runnable接口
相比继承Thread类,实现Runnable接口的好处
1.避免了JAVA单继承的局限性
2.适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码数据有效分离,较好的体现了面向对象的设计思想