多线程的两种创建方式

/**
 * 多线程的创建,方式一:继承Thread类
 * 1.创建继承Thread类的子类
 * 2.重写Thread类的run方法。->将此线程执行的操作声明在run()中
 * 3.创建Thread子类的对象
 * 4.通过此对象调用start方法
 *
 * 例子:遍历100以内的所有偶数
 *
 * @author: qyx
 * @date: 2022-07-21 16:43
 * @desc:
 */


//1.创建继承Thread类的子类
class MyThread extends Thread{

    //2.重写Thread类的run方法。->将此线程执行的操作声明在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方法:1.启动当前线程 2.调用当前线程的run()
        t1.start();
        //问题一:不能通过直接调用run()来直接启动线程
//        t1.run();
        //问题二:再启动一个线程遍历100以内的偶数。不可以还让start的线程去执行。会报illegalThreadException
        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()*******");
            }
        }
    }
}


/**
 * 创建多线程的方式二:实现runnable接口
 * 1.创建一个实现了Runnable接口的类
 * 2.实现类去实现Runnable中的抽象方法:run()
 * 3.创建实现类的对象
 * 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
 * 5.通过Thread类的对象调用start()
 *
 * 比较线程的两种方式。
 * 开发中:优先选择实现Runnable接口的方式
 * 原因:1.没有类的单继承局限性
 *      2.实现的方式更适合处理多个线程有共享数据的情况
 *
 * 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明再run()中。
 * @author: qyx
 * @date: 2022-07-22 15:43
 * @desc:
 */

//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);
        //5.通过Thread类的对象调用start():①启动线程②调用当前线程的run() --->调用了Runnable类型的target的run()
        t1.start();
        t1.setName("线程一");
        //再启动一个线程,遍历100以内的偶数
        Thread t2 = new Thread(mThread);
        t2.setName("线程二");
        t2.start();
    }
}


/**
 * 测试Thread类中常用的方法
 * 1.start():启动当前线程;调用当前线程的run()
 * 2.run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
 * 3.currentThread():是一个静态方法,返回执行当前代码的线程
 * 4.getName():获取当前线程的名字
 * 5.setName():设置当前线程的名字
 * 6.yield():释放当前cpu的执行权
 * 7.join():在线程a中调用线程b的join(),此时线程a进入阻塞状态.直到线程b完全执行完以后,线程a才结束阻塞状态
 * 8.stop():已过时。当执行此方法时,强制结束此线程
 * 9.sleep(long millitime):让当前线程”睡眠“指定的millitime毫秒。在指定的时间之内当前线程是阻塞状态。
 * 10.isAlive():判断当前线程是否存活
 *
 * 线程的优先级
 * 1. 1 5(默认优先级) 10 三种优先级
 * 2.获取和设置优先级
 * 获取优先级:getPriority()
 * 设置优先级:setPriority(int p)
 *
 * 说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。
 * 并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。
 *
 * @author: qyx
 * @date: 2022-07-21 18:47
 * @desc:
 */

class HelloThread extends Thread{

    public HelloThread(String name){
        super(name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){

//                try {
//                    sleep(10);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
            }
            if(i % 20 == 0){
                yield();
            }
        }
    }
}
public class ThreadMethodTest {

    public static void main(String[] args) {
        HelloThread helloThread = new HelloThread("Threa:1");
        helloThread.setName("线程一");
        helloThread.setPriority(Thread.MAX_PRIORITY);
        helloThread.start();
        //给主线程命名
        Thread.currentThread().setName("主线程");
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":"  + i);
            }
//            if(i == 20){
//                try {
//                    helloThread.join();
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
        }
//        System.out.println(helloThread.isAlive());
    }
}



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

/**
 *
 * 创建线程的方式三:实现Callable接口。
 *
 * 1.创建一个实现Callable接口的实现类
 * 2.实现call方法
 * 3.创建callable接口实现类的对象
 * 4.创建FutureTask对象,并将实现类作为参数传入
 * 5.创建线程Thread.start
 * 6.如果需要获取返回值调用Futuretask.get()对象返回Object
 *
 * callable比runnable的好处
 * 1.可以有返回值
 * 2.可以抛出异常
 * 3.支持泛型
 * @author: qyx
 * @date: 2022-07-23 23:37
 * @desc:
 */

class NumThread implements Callable{

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for(int i = 1; i <= 100; i++){
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
                sum += i;
            }
        }
        return sum;
    }
}
public class ThreadNew {
    public static void main(String[] args) {
        NumThread numThread = new NumThread();
        FutureTask futureTask = new FutureTask(numThread);
        new Thread(futureTask).start();
        try {
            Object sum = futureTask.get();
            System.out.println("总和为" + sum);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}




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

/**
 * 创建线程的方式四:使用线程池
 *
 * 好处:
 * 1.提高响应速度
 * 2.降低资源消耗
 * 3.便于线程管理
 *
 *
 *
 * 创建多线程一共有四种方式
 *
 * @author: qyx
 * @date: 2022-07-24 23:54
 * @desc:
 */
class NumberThread implements Runnable{

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

class NumberThread2 implements Runnable{

    @Override
    public void run() {
        for (int i = 1; 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);
        //线程管理
        ThreadPoolExecutor service1 = (ThreadPoolExecutor)service;
        service1.setCorePoolSize(15);//核心池的大小
        service1.setMaximumPoolSize(12);//最大线程数
//        service1.setKeepAliveTime();线程没有任务时最多保持多长时间终止

        //设置线程池的属性
        System.out.println(service.getClass());
        //2.执行指定的线程的操作。
        NumberThread numberThread = new NumberThread();
        service.execute(numberThread);//适合适用于Runnable
        service.execute(new NumberThread2());//适合适用于Runnable
//        service.submit(new Callable(){});//适合适用于Callable
        //关闭县城连接池
        service.shutdown();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值