实现runable接口
并使用Thread.start调用
//使用实现 runable接口方式 和 匿名内部类实现多线程
public class HowBuildConcurrency implements Runnable {
@Override
public void run() {
try {
Thread.sleep((int)(Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId() + " " + Thread.currentThread().getName());
}
public static void main(String[] args) {
for (int i = 0; i < 10 ; i++) {
Thread thread = new Thread(new HowBuildConcurrency());
thread.start();
}
}
}
匿名内部类方式
public static void main(String[] args) {
for (int i = 0; i < 10 ; i++) {
new Thread(){
public void run() {
System.out.println( "匿名内部类 创建多线程" +Thread.currentThread().getId() + " " + Thread.currentThread().getName());
}
}.start();
}
}
继承Thread类 实现多线程
//继承方式创建多线程
public class HowBuildConcurrency2 extends Thread{
@Override
public void run() {
System.out.println( "继承thread 创建线程" +Thread.currentThread().getId() + " " + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10000 ; i++) {
HowBuildConcurrency2 howBuildConcurrency2 = new HowBuildConcurrency2();
howBuildConcurrency2.start();
}
}
}