深入理解JAVA创建线程的方法Thread和Runnable

/**
 * 第一种创建线程的方式
 * 继承Thread类,重写run方法
 * @author wangxin
 *
 */
public class ThreadDemo1 {
	public static void main(String[] args) {
		Thread t1=new MyThread1();
		Thread t2=new MyThread2();
		//start方法把线程拉入到线程调度,这时,线程进入runnable状态,
		/*
		 * 等待线程调度分配时间片段
		 * 当线程调度将时间分配给当前线程,该方法的run方法才开始被执行。
		 * 当线程调度将时间片段执行完毕,线程结束最终被回收
		 * 在线程的run 方法执行期间,该线程处于走走停停。
		 */
		t1.start();
		t2.start();
	}
}
class MyThread1 extends Thread{
	public void run(){
		for(int i=0;i<1000;i++){
			System.out.println("你是谁啊"+i);
		}
	}
}
class MyThread2 extends Thread{
	public void run(){
		for(int i=0;i<1000;i++){
			System.out.println("我是歪果仁 "+i);
		}
	}
}


 
  
/**
 * 第二种创建线程的方法
 * 定义线程体Runnable
 * @author huawangxin
 *
 */
public class ThreadDemo2 {
	public static void main(String[] args) {
		Runnable runn1=new MyRunnable1();
		Runnable runn2=new MyRunnable2();
		Thread t1=new Thread(runn1);
		Thread t2=new Thread(runn2);
		t1.start();
		t2.start();
	}
}
class MyRunnable1 implements Runnable{
	public void run(){
		for(int i=0;i<1000;i++){
			System.out.println("你是谁啊"+i);
		}
	}
}
class MyRunnable2 implements Runnable{
	public void run(){
		for(int i=0;i<1000;i++){
			System.out.println("我是歪果仁 "+i);
		}
	}
}
/**
 * 使用匿名内部类的形式创建线程
 * @author wangxin
 *
 */
public class ThreadDemo3 {
	public static void main(String[] args) {
		//1
		Thread t1=new Thread(){
			public void run(){
				for(int i=0;i<1000;i++){
					System.out.println("你是谁");
				}
			}
		};
		//2
		Runnable runn=new Runnable() {
			public void run() {
				for(int i=0;i<1000;i++){
						System.out.println("我是歪果仁");
					}
				}
		};
		Thread t2=new Thread(runn);
		t1.start();
		t2.start();
	}
}



上述如果有不对或者补充的地方,请大家批评和指教,谢谢。

你可能感兴趣的:(java)