创建多线程的方式

时间:2022-05-07 15:31:06

创建多线程有三种方式来创建:
1.继承Thread类
2.实现Runnable接口
3.使用Executor框架来创建线程池

一.继承Thread类

package com.test;

/**
* Created by admin on 2017/6/5 10:16.
*
*/
public class DemoThread extends Thread {
private String name;

DemoThread(String name) {
this.name = name;
}

@Override
public void run() {
for (int i = 0; i < 40; i++) {
System.out.println(name
+ ":" + i);
}
}

public static void main(String[] args) {
new DemoThread("线程1").start();
new DemoThread("线程2").start();
new DemoThread("线程3").start();
}
}

二.实现Runnable接口

package com.test;

/**
* Created by admin on 2017/6/5 10:16.
*/
public class DemoThread implements Runnable {

@Override
public void run() {
for (int i = 0; i < 40; i++) {
System.out.println(Thread.currentThread().getName()
+ ":" + i);
}
}

public static void main(String[] args) {
DemoThread d1
= new DemoThread();
Thread t1
= new Thread(d1, "线程1");
Thread t2
= new Thread(d1, "线程2");
Thread t3
= new Thread(d1, "线程3");
t1.start();
t2.start();
t3.start();
}
}

 三.使用线程池创建

package com.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Created by admin on 2017/6/5 10:16.
*/
public class DemoThread {
public static void main(String[] args) {
//固定大小的线程池,如果线程数量大于固定值,多的线程则会等待
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(()
-> {
for (int i = 0; i < 40; i++) {
System.out.println(
"线程1:" + i);
}
});
pool.execute(()
-> {
for (int i = 0; i < 40; i++) {
System.out.println(
"线程2:" + i);
}
});
pool.execute(()
-> {
for (int i = 0; i < 40; i++) {
System.out.println(
"线程3:" + i);
}
});
}

}