线程的创建方式

一、继承Thread

1、创建类继承Thread

2、重写类的run方法

3、调用时创建实例对象然后调用start方法

举例:

class MyThread extends Thread{
    @Override
    public void run() {
        for(int i=0;i<10;i++){
            System.out.println("老王,要被打死");
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("复活啦");
    }
}

二、实现Runnable接口

1、让类实现Runnable接口

2、重写run方法

3、调用时实现实例对象

4、创建一个Thread对象,把示例对象当做参数传给示例对象

5、调用Thread实例对象的start方法

class MyRunnable implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+"---------转世"+i);
        }
    }
}
public class Demo1 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        MyRunnable myRunnable1 = new MyRunnable();
        Thread thread = new Thread(myRunnable,"老铁");
        Thread thread1 = new Thread(myRunnable1,"隔壁老王");
        thread.start();
        thread1.start();
        System.out.println("完啦");
    }
}

三、实现Callable接口

1、实现Callable接口,有返回值类型

2、重写call方法

3、创建实现类的实例对象

4、 创建FutureTask实例对象,并把实例对象当做参数传给FutureTask对象

5、创建Thread对象,把FutureTask实例当做参数传给Thread

6、调用thread实例的start方法

class demoThread implements Callable<Integer> { 
@Override	
public Integer call() throws Exception {
    int n = 100;		
    return Integer.valueOf(n);
    }
}

public static void main(String[] args) {
    demoThread th= new demoThread ();
    FutureTask<Integer> task = new FutureTask<>(th);
    Thread thread = new Thread(task);
    thread.start();
    System.out.println(" n :" + task.get());
}

四、线程池获取

1、创建Thread对象并且重写run方法

2、使用执行器获取executors获取线程池

3、调用executors的execute方法,并把thread示例对象当做参数传入

class MyRunnable implements Runnable{
    @Override
    public void run() {
     System.out.println(Thread.currentThread().getName()+"---------执行");
    }
}
public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(new MyRunnable ());
}

>>>一般常用的线程池有以下两种:

1、newCachedThreadPool:创建一个可缓存的线程池,超出长度当有空闲线程的时候回收,没有的时候创建

2、newFixedThreadPoo:创建一个定长的线程池,固定的长度,当超出长度的时候,线程在队列中等待

猜你喜欢

转载自blog.csdn.net/qq_40757296/article/details/82942014