java 创建线程的三种方法(Thread,Runnable,Callable)ExecutorService

1.继承Thread类
2.实现Runnable接口
3.实现Callable接口
4.线程池

1.继承Thread类
package com.chen;

// 创建线程的方式:继承Thread,重写run(),调用start()开启线程
// 注意,线程开启不一定立即执行,由cpu调度执行
public class TestThread2 extends Thread{
@Override
public void run(){
for (int i = 0; i <20 ; i++) {
System.out.println("submain"+i);
}
}

public static void main(String[] args) {
    TestThread2 t2=new TestThread2();
    t2.start();

    for (int i = 0; i <20 ; i++) {
        System.out.println("main"+i);
    }
}

}

2.实现Runnable接口
package com.chen;

// 创建线程的方式二:实现runnable,重新run(),执行线程需要丢入runable接口实现类调用start()
public class TestThread3 implements Runnable {
@Override
public void run(){
for (int i = 0; i <20 ; i++) {
System.out.println("submain"+i);
}
}
private String name;

public void TestThread3(String name){
    this.name=name;
}

public static void main(String[] args)
{
    TestThread3 t3=new TestThread3();
     new Thread(t3,"aa").start();
     new Thread(t3,"bb").start();
     new Thread(t3,"cc").start();

// main,submain交替执行
for (int i = 0; i <20 ; i++) {
System.out.println("main"+i);
}

}

}

3.实现Callable接口

4.线程池
package com.chen;

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

public class TestPool {
public static void main(String[] args) {
// 创建服务,创建线程
// newFixedThreadPool 参数为线程池大小 10
ExecutorService service = Executors.newFixedThreadPool(10);

    // 执行
    service.execute(new MyThread());
    service.execute(new MyThread());
    service.execute(new MyThread());
    service.execute(new MyThread());

    // 关闭链接
    service.shutdown();
}

}

class MyThread implements Runnable{
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
}

posted @ 2024-11-18 23:07  大树2  阅读(3)  评论(0编辑  收藏  举报