多个线程
package com.chen;
public class MyClass {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
//创建一个Thread对象
Thread t1 = new Thread(cat);
Thread t2 = new Thread(dog);
t1.start();
t2.start();
}
}
class Cat implements Runnable{
public void run(){
int i = 0;
while(i < 10){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Cat:" + i);
++i;
}
}
}
class Dog implements Runnable{
public void run(){
int j = 0;
while(j < 10){
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Dog:" + j);
++j;
}
}
}
所以我们尽可能的使用实现Runnable接口的方式来创建线程。