方式1:继承Thread类;
步骤:
1):定义一个类A继承于java.lang.Thread类.
2):在A类中覆盖Thread类中的run方法.
3):我们在run方法中编写需要执行的操作---->run方法里的,线程执行体.
4):在main方法(线程)中,创建线程对象,并启动线程.
创建线程类对象: A类 a = new A类();
调用线程对象的start方法: a.start();//启动一个线程
注意:千万不要调用run方法,如果调用run方法好比是对象调用方法,依然还是只有一个线程,并没有开启新的线程.
public class Thread01 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
Thread01 t1 = new Thread01();
Thread01 t2 = new Thread01();
t1.start();
t2.start();
方式2:实现Runnable接口;
步骤:
1):定义一个类A实现于java.lang.Runnable接口,注意A类不是线程类.
2):在A类中覆盖Runnable接口中的run方法.
3):我们在run方法中编写需要执行的操作---->run方法里的,线程执行体.
4):在main方法(线程)中,创建线程对象,并启动线程.
创建线程类对象: Thread t = new Thread(new A());
调用线程对象的start方法: t.start();
public class MyThread extends OtherClass implements Runnable {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
使用匿名内部类来创建线程:
只适用于某一个类只使用一次的情况.
public class AnonymousInnerClass {
public static void main(String[] args) {
for (int i = 0; i < 33; i++) {
System.out.println("打游戏" + i);
if (i == 10) {
//创建匿名线程对象
new Thread() {
public void run() {
for (int j = 0; j < 33; j++) {
System.out.println("音乐" + j);
}
}
}.start();
}
}
}
}
public class AnonymousInnerClass2 {
public static void main(String[] args) {
// 主线程 :运行游戏
for (int i = 0; i < 33; i++) {
System.out.println("打游戏" + i);
if (i == 10) {
new Thread(new Runnable(){
public void run(){
for (int j = 0; j < 33; j++) {
System.out.println("==============="+ j);
}
}
}).start();
}
}
}
}