java创建线程的几种方式

一、继承Thread类

使用方法:

1.创建一个继承Thread的子类(便于写入线程的执行方法)

2.重写Thread中的run()方法(作为线程的执行方法)

3.在使用时创建第一步时子类的实例对象

4.调用该实例对象的start()方法

代码展示(遍历100以内的数):

package atguigu.java;

//1.创建一个继承于Thread类的子类
class MyThread extends Thread {
    //2.重写Thread类的run()
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}


public class ThreadTest {
    public static void main(String[] args) {
        //3.创建Thread类的子类的对象
        MyThread t1 = new MyThread();

        //4.通过此对象调用start():①启动当前线程 ② 调用当前线程的run()
        t1.start();

        /*问题一:我们不能通过直接调用run()的方式启动线程,
        这种方式只是简单调用方法,并未新开线程*/
        //t1.run();

        /*问题二:再启动一个线程,遍历100以内的偶数。
        不可以还让已经start()的线程去执行。会报IllegalThreadStateException*/
        //t1.start();

        //重新创建一个线程的对象
        MyThread t2 = new MyThread();
        t2.start();

        //如下操作仍然是在main线程中执行的。
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i + "***********main()************");
            }
        }
    }
}

由于cpu的分页操作,所以最终结果会是几个线程的混合输出,如:

线程一:0

线程二:0

线程一:2

线程一:4

线程一:6

线程二:2

如此无规律的混合交替执行。

二、实现Runnable接口

步骤:

1、创建一个实现了Runnable接口的类

2、实现类去实现Runnable中的抽象方法:run()

3、创建实现类的对象

4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象

5、通过Thread类的对象调用start()

①启动线程

②调用当前线程run() ->调用了Runnable的target的run()

示例代码(遍历100以内的所有偶数):

package atguigu.java;

//1.创建一个实现了Runnable接口的类
class MThread implements Runnable {

    //2.实现类去实现Runnable中的抽象方法:run()
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

public class ThreadTest1 {

    public static void main(String[] args) {
        //3.创建实现类的对象
        MThread mThread = new MThread();

        //4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread t1 = new Thread(mThread);
        t1.setName("线程1");

        //5.通过Thread类的对象调用start():① 启动线程 ②调用当前线程的run()-->调用了Runnable类型的target的run()
        t1.start();

        //再启动一个线程,遍历100以内的偶数
        Thread t2 = new Thread(mThread);
        t2.setName("线程2");
        t2.start();
    }

}

输出结果:

线程1:0

线程1:2

线程1:4

线程1:6

线程1:8

线程2:0

线程1:10

继承Thread和实现Runnable对比:

  • 开发中有限选择实现Runnable接口的方式
  • 原因:

        (1)实现的方式没有类的单继承的局限性

        (2)实现的方式更适合来处理多个线程有共享数据的情况

  • 相同点:两种方式都需要重写run() ,将线程要执行的逻辑声明在run()中

三、实现Callable接口

步骤:

1、创建一个实现Callable的实现类

2、实现call方法,将此线程需要执行的操作声明在call()中

3、创建Callable接口实现类的对象

4、将此Callable接口实现类的对象作为传递到Future Task构造器中,创建Future Task的对象

5、将Future Task的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()

6、获取Callable中的call方法的返回值

实现Callable接口的方式创建线程的强大之处

  • call() 可以有返回值
  • call()可以抛出异常,被外面的操作捕获,获取异常的信息
  • Callable是支持泛型的

示例代码:

package com.atguigu.java2;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//1.创建一个实现Callable的实现类
class NumThread implements Callable {
    //2.实现call方法,将此线程需要执行的操作声明在call()中
    @Override
    public Object call() throws Exception {
        int sum = 0;
        //把100以内的偶数相加
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}

public class ThreadNew {
    public static void main(String[] args) {    
        //3.创建Callable接口实现类的对象
        NumThread numThread = new NumThread();

        //4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
        FutureTask futureTask = new FutureTask(numThread);

        //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
        new Thread(futureTask).start();

        try {
            //6.获取Callable中call方法的返回值
            //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
            Object sum = futureTask.get();
            System.out.println("总和为:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

示例代码:

package com.jian8.juc.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("Callable come in");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1024;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //使用构造方法:FutureTask(Callable<V> callable)
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread());

        new Thread(futureTask, "AAA").start();
        //new Thread(futureTask, "BBB").start();//复用,直接取值,不要重启两个线程
        //PS:多个线程来抢一个futureTask,里面的计算方法call()只计算一次,要想多次算,要创建多个FutureTask<V>对象

        int a = 100;
        int b = 0;

        //b = futureTask.get();//要求获得Callable线程的计算结果,如果没有计算完成就要去强求,会导致堵塞,直到计算完成
        while (!futureTask.isDone()) {//当futureTask完成后取值
            b = futureTask.get();
        }
        System.out.println("Result=" + (a + b));
    }
}

四、使用线程池

线程池的好处:

1、提高响应速度(减少了创建新线程的时间)

2、降低资源消耗(重复利用线程池中线程,不需要每次都创建)

3、便于线程管理

核心参数:

  • corePoolSize:核心池的大小
  • maximumPoolSize:最大线程数
  • keepAliveTime:线程没有任务时最多保持多长时间后停止
  • unit:空闲线程的存活单位
  • workQueue:工作队列
  • threadFactory:线程工厂
  • handler:拒绝策略

示例代码:

package com.atguigu.java2;

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

class NumberThread implements Runnable {
    @Override
    public void run() {
        //遍历100以内的偶数
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

class NumberThread1 implements Runnable {
    @Override
    public void run() {
        //遍历100以内的奇数
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}


public class ThreadPool {

    public static void main(String[] args) {
        //1. 提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        //输出class java.util.concurrent.ThreadPoolExecutor
        System.out.println(service.getClass());

        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //自定义线程池的属性
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();

        //2. 执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread());//适用于Runnable
        service.execute(new NumberThread1());//适用于Runnable
//        service.submit(Callable callable);//适合使用于Callable

        //3. 关闭连接池
        service.shutdown();
    }

}

输出结果: 

pool-1-thread-2:63

pool-1-thread-2:65

pool-1-thread-2:67

pool-1-thread-1:82

pool-1-thread-2:69

pool-1-thread-2:71

五、使用匿名类 

Thread thread = new Thread(new Runnable() {
	@Override
	public void run() {
		// 线程需要执行的任务代码
		System.out.println("子线程开始启动....");
		for (int i = 0; i < 30; i++) {
			System.out.println("run i:" + i);
		}
	}
});
thread.start();

或者

new Thread(() -> {
	System.out.println(Thread.currentThread().getName() + "\t上完自习,离开教室");
}, "MyThread").start();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值