实现线程从方式
1,将类声明为 Thread 的子类,该子类应重写 Thread 类的 run 方法
package com.demo.code.threaddemo;
public class Demo01 {
public static void main(String[] args) {
MyThread r = new MyThread();
r.start();
/** main线程 */
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
使用匿名内部类简化写法
package com.demo.code.threaddemo;
public class Demo01 {
public static void main(String[] args) {
Thread r = new Thread() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
};
r.start();
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
2,声明实现 Runnable 接口的类
package com.demo.code.runnabledemo;
public class Demo01 {
public static void main(String[] args) {
MyRunnableImpl myRunnable = new MyRunnableImpl();
Thread thread = new Thread(myRunnable);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
class MyRunnableImpl implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
使用匿名内部类简化写法
package com.demo.code.runnabledemo;
public class Demo01 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}