1.创建多线程的方式
继承Thread重写run()方法
//方式1
public class Demo1 extends Thread{
//重写的是父类Thread的run()
public void run() {
System.out.println(getName()+"is running...");
}
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
Demo1 demo2 = new Demo1();
demo1.start();
demo2.start();
}
2.实现runable接口
/**
* 第二种创建启动线程的方式
* 实现Runnale接口
*/
public class Demo2 implements Runnable{
//重写的是Runnable接口的run()
public void run() {
System.out.println("implements Runnable is running");
}
public static void main(String[] args) {
Thread thread1 = new Thread(new Demo2());
Thread thread2 = new Thread(new Demo2());
thread1.start();
thread2.start();
}
}
3.定时线程
public class Demo3 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时任务延迟0(即立刻执行),每隔1000ms执行一次");
}
}, 0, 1000);
}
}
4.带有返回值的线程Callable
public class Demo4 implements Callable<String>{
public String call() throws Exception {
System.out.println("正在执行新建线程任务");
Thread.sleep(2000);
return "新建线程睡了2s后返回执行结果";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Demo4 d = new Demo4();
//call()只是线程任务,对线程任务进行封装
FutureTask<String> task = new FutureTask<>(d);
Thread t = new Thread(task);
t.start();
System.out.println("提前完成任务...");
//获取任务执行后返回的结果
String result = task.get();
System.out.println("线程执行结果为"+result);
}
}
5.线程池
public class Demo5 {
public static void main(String[] args) {
//创建带有5个线程的线程池
//返回的实际上是ExecutorService,而ExecutorService是Executor的子接口
Executor threadPool = Executors.newFixedThreadPool(5);
for(int i = 0 ;i < 10 ; i++) {
threadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+" is running");
}
});
}
}
}
线程池总共有几种线程池
Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
public class ThreadPoolExecutorTest {
public static void main(String[] args ) {
ExecutorService cacheThreadPool =Executors.newCachedThreadPool();
for(int i =1;i<=5;i++){
final int index=i ;
try{
Thread.sleep(1000);
}catch(InterruptedException e ) {
e.printStackTrace();
}
cacheThreadPool.execute(new Runnable(){
@Override
public void run() {
System.out.println("第" +index +"个线程" +Thread.currentThread().getName());
}
});
}
}
}
newFixedThreadPool创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ExecutorService fixedThreadPool =Executors. newFixedThreadPool(3);
for (int i =1; i<=5;i++){
final int index=i ;
fixedThreadPool.execute(new Runnable(){
@Override
public void run() {
try {
System.out.println("第" +index + "个线程" +Thread.currentThread().getName());
Thread.sleep(1000);
} catch(InterruptedException e ) {
e .printStackTrace();
}
}
});
}
}
}
newScheduledThreadPool创建一个定长线程池,支持定时和周期性任务执行
//延迟执行示例代码:
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3);
scheduledThreadPool.schedule(newRunnable(){
@Override
public void run() {
System.out.println("延迟三秒");
}
}, 3, TimeUnit.SECONDS);
}
}
//表示延迟3秒执行。
//定期执行示例代码:
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3);
scheduledThreadPool.scheduleAtFixedRate(newRunnable(){
@Override
public void run() {
System.out.println("延迟1秒后每三秒执行一次");
}
},1,3,TimeUnit.SECONDS);
}
}
//表示延迟1秒后每3秒执行一次。
newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO,LIFO,优先级)执行。
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ExecutorService singleThreadPool= Executors.newSingleThreadExecutor();
for(int i=1;i<=5;i++){
int index=i;
singleThreadPool.execute(new Runnable(){
@Override
public void run() {
try{
System.out.println("第"+index+"个线程");
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
} });
}
}
}