Java中常见的创建线程的方法

方法一:继承Thread并重写run方法来定义线程要执行的任务。

package day09;
/**
 * 第一种创建线程的方式
 * 继承Thread并重写run方法来定义线程要执行的任务。
 * @author kaixu
 *
 */
public class ThreadDemo1 {

	public static void main(String[] args) {
		MyThread1 thread1 = new MyThread1();
		MyThread2 thread2 = new MyThread2();
		/*
		 * 七点线程要指定start方法,而不是直接调用run方法。
		 * run方法是线程要执行的任务。当线程的start方法被
		 * 调用后,线程进入runnable状态,一旦获取CPU时间
		 * run方法就会被自动调用。
		 */
		thread1.start();
		thread2.start();
	}

}
/**
 * 第一种创建线程的方式有两个不足:
 * 1.由于java是单继承机制,那么当继承了Thread后就无法再继承其他类。
 * 
 * 2.由于继承Thread后重写run方法规定了线程执行的任务,这导致线程与
 * 任务之间存在必然的耦合关系,不利用线程资源的重用。
 * @author kaixu
 *
 */
class MyThread1 extends Thread{
	public void run() {
		for(int i=0;i<1000;i++){
			System.out.println("你是谁啊?");
		}
	}
}
class MyThread2 extends Thread{
	public void run() {
		for(int i=0;i<1000;i++){
			System.out.println("我是查水表的。");
		}
	}
}

方法二:实现Runnable接口并重写run方法。

package day09;
/**
 * 第二种创建线程的方式
 * 实现Runnable接口并重写run方法。
 * @author kaixu
 *
 */
public class ThreadDemo2 {

	public static void main(String[] args) {
		//单独定义任务
		Runnable runnable1 = new MyRunnabe1();
		Runnable runnable2 = new MyRunnabe2();
		Thread thread1 = new Thread(runnable1);
		Thread thread2 = new Thread(runnable2);
		thread1.start();
		thread2.start();
	}

}
class MyRunnabe1 implements Runnable{
	public void run() {
		for(int i=0;i<1000;i++){
			System.out.println("你是谁啊?");
		}
	}
}
class MyRunnabe2 implements Runnable{
	public void run() {
		for(int i=0;i<1000;i++){
			System.out.println("我是查水表的。");
		}
	}
}

方法三:使用匿名内部类的形式来完成方式一与方式二的线程创建。

package day09;

/**
 * 使用匿名内部类的形式来完成方式一与方式二的线程创建。
 * @author kaixu
 *
 */
public class ThreadDemo3 {

	public static void main(String[] args) {
		//方式一
		Thread t1 = new Thread(){
			public void run(){
				for(int i=0;i<1000;i++){
					System.out.println("你是谁啊?");
				}
			}
		};
		t1.start();
		
		//方式二
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i=0;i<1000;i++){
				System.out.println("我是查水表的。");
				}
			}
		}).start();
	}
}

完。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值