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

首选方式

new Thread() {
    public void run() {
		System.out.println("线程开始。。。");
    }
}.start();

 

 

 

 
/** * 第一种创建线程的方式 * 继承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); } } }我是歪果仁 "+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);
		}
	}
}
	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();
	}
}

 

 

 

 

 

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值