1.继承 Thread类
1)自定义一个类,该类继承Thread类
2)重写run()方法
3)在主线程中创建该类的子类对象
` 4)调用start()方法(启动线程)
/*
* 分析:
* 1.继承 Thread类
* 1)自定义一个类,该类继承Thread类
* 2)重写run()方法
* 3)在主线程中创建该类的子类对象
* ` 4)启动线程(调用start()方法)
* 2
* */
public class TwoWaysToCreateThreads {
public static void main(String[] args) {
//在主线程中创建该类的子类对象
MyThread mt = new MyThread();
MyThread mt1 = new MyThread();
mt.setName("曹操");
mt1.setName("刘备");
//启动线程(调用start()方法)
mt.start();
mt1.start();
}
}
//自定义一个类,该类继承Thread类
class MyThread extends Thread{
//重写run()方法
public void run() {
for (int x = 0; x < 100; x++) {
System.out.println(this.getName()+":"+x);
}
}
}
2.实现Runnable接口
1)自定义一个接口,实现Runnable
2)重写run()方法
3)在主函数中创建实现类对象
4)创建线程Thread对象
5)调用start()方法
/*分析:
1)自定义一个接口,实现Runnable
2)重写run()方法
3)在主函数中创建实现类对象
4)创建线程Thread对象
5)调用start()方法
* */
public class XianChengRunnable {
public static void main(String[] args) {
//3)在主函数中创建实现类对象
MyRunnable mt = new MyRunnable();
//4)创建线程Thread对象
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
t1.setName("靓仔");
t2.setName("靓女");
//5)调用start()方法
t1.start();
t2.start();
}
}
//1)自定义一个接口,实现Runnable
public class MyRunnable implements Runnable {
//2)重写run()方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"-----"+i);
}
}
}