/*
创建一个新的线程
*/
/*
class Testthread{
public static void main(String[] args){
//第三步创建Thread子类对象
NewThread a = new NewThread("小强");
NewThread a1 = new NewThread("shbi");
//第四步调用Thread中start方法
a.start();
a1.start();
}
}
//第一步创建Thread子类
class NewThread extends Thread{
private String name;
NewThread(String name){
this.name = name;
}
//第二步重写run方法
public void run(){
for (int x = 0;x < 12 ;x++ ){
System.out.println(name+"........"+x);
}
}
}
*/
/*
需求: 第二种创建线程的方法
第一种新建线程的方法需要继承Thread,然后重写Thread中的run()方法.
然后新建子类对象,调用start()方法,作用是使线程开始执行;java虚拟机调用
该线程的run方法.
然而第一种新建现成的方法有局限性,如果一个类中有需要实现多线程的
方法,但是这个类已经有其父类,那么就不能再继承Thread了
此时,我们就有了第二种新建线程的方法.实现Runnable接口.
第二种新建线程的步骤:使已经有父类的子类实现Runnable接口.然后新建
Thread对象,然后调用Thread中的Thread(Runnable target)构造方法,最后
调用start方法.
*/
class RunnableThread{
public static void main(String[] args){
//新建Dog对象
Dog d = new Dog("旺财","黄色");
Dog d1 = new Dog("小白","白色");
//新建Thread对象,把子类对象引用传入Thread(Runnable target)
Thread t = new Thread(d);
Thread t1 = new Thread(d1);
t.start();
t1.start();
}
}
class Animale{
}
class Dog extends Animale implements Runnable{
private String name;
private String furColor;
Dog(String name,String furColor){
this.name = name;
this.furColor = furColor;
}
public void run(){//run方法中包含了需要线程执行的方法
for (int x =0;x < 15 ;x++ ){
System.out.println(name+" "+furColor);
}
}
} |
|