创建线程

在创建线程有两种方法:使用Thread类和使用Runnable接口。在使用Runnable接口需要建立一个Thread实例。因此,无论是通富哦Thread类还是Runnable接口建立线程,都必须建立Thread类或其子类的实例。

class  Thread1 extends Thread{
	public void run(){
		System.out.println(Thread.currentThread().getName());
	}
}
class Thread2 extends Thread{
	public Thread2(String name){
		super(name);
	}
	public void run(){
		System.out.println(Thread.currentThread().getName());
	}
}
public class ThreadDemo{
	public static void main(String args[]){
		Thread1 thread1=new Thread1();
		Thread2 thread2=new Thread2("thread2");
		thread1.start();
		thread2.start();
		System.out.println(Thread.currentThread().getName());
	}
}

通过实现RunnableDemo的类

class RenWu implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("当前线程:"+Thread.currentThread().getName());
		for(int i=0;i<30;i++){
			System.out.println("A");
		}
	}
	
}

public class RunnableDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RenWu rw=new RenWu();
		Thread thread=new Thread(rw);
		thread.start();
		System.out.println(Thread.currentThread().getName());
		for(int i=0;i<30;i++){
			System.out.println("c");
		}
	}

}

猜你喜欢

转载自blog.csdn.net/Hydra_shuang/article/details/79829756