java多线程学习1-继承Thread类和实现Runnable接口来创建线程

时间:2021-02-09 17:27:53
package learn.thread;

/**
* 用Thread类来创建线程,start()方法(会自动调用run()方法)和run()方法,
* 实现自己的线程要重写run()方法,
* @author whitetiger
*
*/

public class LearnOne {

public static void main(String[] args) {
Demo demo = new Demo();
demo.start(); //启动线程
while(true){
System.out.println(Thread.currentThread().getName()+">>>>>main 方法中");
}
}


}

class Demo extends Thread{


@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+"learnOne中");
}

}

}

package learn.thread;/**  * 实现runnable接口,一定要实现run方法,除非是抽象类 * 申明new A();* 调用 new Thread(A).start(); * 实现自己的线程要重写run()方法 * @author whitetiger  * */public class LearnTwo {

   public static void main(String[] args) {  Demo2 de= new Demo2();  new Thread(de).start();  while(true){   System.out.println(Thread.currentThread().getName()+">>>>main 线程中");  }     }  }

class Demo2 implements Runnable{

 @Override public void run() {  // TODO Auto-generated method stub  while(true){   System.out.println(Thread.currentThread().getName()+"线程中");     } } }