方法一:继承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();
}
}
完。