1、实现 Thread类
此方法需要实现Thread的run()方法
package com.demo;
public
class ExtendsThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
在主方法里调用start()方法启动
线程
package com.demo;
public class ExcutorClass {
public static void main(String[] args) {
ExtendsThread extendsThread = new ExtendsThread();
extendsThread.start();
}
}
执行结果:
Thread-0:0
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
2、实现
Runnable接口
通过实现Runnable接口,重写run()方法
package com.demo;
public class ImplementsRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
在主方法里启动你的线程
package com.demo;
public class ExcutorClass {
public static void main(String[] args) {
Runnable runnable = new ImplementsRunnable();
Thread
thread = new Thread(runnable);
thread.start();
}
}
结果:
Thread-0:0
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
3、通过线程池的方式来创建线程
package com.demo;
import java.util.concurrent.Executor
Service;
import java.util.concurrent.Executors;
public class ExcutorClass {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
ImplementsRunnable implementsRunnable = new ImplementsRunnable();
threadPool.execute(implementsRunnable);
}
}
}
执行结果:
pool-1-thread-3:0
pool-1-thread-1:0
pool-1-thread-2:0
pool-1-thread-1:1
pool-1-thread-3:1
pool-1-thread-2:1
pool-1-thread-1:2
pool-1-thread-3:2
pool-1-thread-2:2
pool-1-thread-1:3
pool-1-thread-2:3