多线程-1

多线程的相关概念


多线程的概念和优缺点
概念
多线程(Multi Thread):是指从软件或者硬件上实现多个线程并发执行的技术。本章主要讲软件上实现多线程技术。
优点

缺点

多线程实现方式
继承Thread

package com.aaa.mt.demo1;

/**
 * @FileName: MTExtendsThread
 * @Description:
 * @Author: zhz
 * @CreateTime: 2024/11/23 9:55
 * @Version: 1.0.0
 */
public class MTExtendsThread  extends  Thread{
    int i=10;
    /**
     * 线程执行任务的方法(要执行任务的代码都在这方法中)
     */
    @Override
    public void run() {
        //返回当前正在执行的线程对象
        Thread thread = Thread.currentThread();
        //getName()返回此线程的名称。
        System.out.println("线程:"+thread.getName()+",正在执行。。。。。。");
        //打印1-5
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }

    /*public static void main(String[] args) {
        System.out.println("线程:"+Thread.currentThread().getName()+",正在执行。。。。。。");
        MTExtendsThread mtExtendsThread =new MTExtendsThread();
        mtExtendsThread.start();
        MTExtendsThread mtExtendsThread1 =new MTExtendsThread();
        mtExtendsThread1.start();
    }*/
}

实现Runnable接口

package com.aaa.mt.demo1;

/**
 * @FileName: MTImplementsRunnable
 * @Description:
 * @Author: zhz
 * @CreateTime: 2024/11/23 10:52
 * @Version: 1.0.0
 */
public class MTImplementsRunnable  implements Runnable{
    int i=10;
    @Override
    public void run() {
        //currentThread()返回当前正在执行的线程对象
        //getName()返回此线程的名称。
        System.out.println("线程:"+Thread.currentThread().getName()+",正在执行。。。。。。");
        //打印1-5
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        System.out.println("线程:"+Thread.currentThread().getName()+",正在执行。。。。。。");
        MTImplementsRunnable mtImplementsRunnable =new MTImplementsRunnable();
        //因为Runnable中没有start方法,借助Thread启动线程
        //多态  要的接口,实际传递的是子类
        Thread thread1 = new Thread(mtImplementsRunnable);
        thread1.start();
        Thread thread2 = new Thread(mtImplementsRunnable);
        thread2.start();
    }
}

实现Callable接口

package com.aaa.mt.demo1;

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

/**
 * @FileName: MTImplementsCallable
 * @Description:
 * @Author: zhz
 * @CreateTime: 2024/11/23 10:58
 * @Version: 1.0.0
 */
public class MTImplementsCallable  implements Callable<String> {
    @Override
    public String call() throws Exception {
        //currentThread()返回当前正在执行的线程对象
        //getName()返回此线程的名称。
        System.out.println("线程:"+Thread.currentThread().getName()+",正在执行。。。。。。");
        //打印1-5
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
        String randomStr = UUID.randomUUID().toString();
        System.out.println("线程的业务方法中,生成字符串:"+randomStr);
        //System.out.println(1/0);
        return randomStr;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("线程:"+Thread.currentThread().getName()+",正在执行。。。。。。");
        //实例化对象
        MTImplementsCallable mtImplementsCallable =new MTImplementsCallable();
        // FutureTask  是Runnable 和Future接口的子类
           //  Future
        // FutureTask 作用: 1,因为他是Runnable的子类,new Thread需要该子类, 所以能用来启动线程
        //                  2,Future 可以用来获取业务执行方法的返回值  获取异常
        FutureTask<String> futureTask =new FutureTask(mtImplementsCallable);
        //使用futureTask实例化Thread
        Thread thread = new Thread(futureTask);
        thread.start();
        String returnValue = futureTask.get();
        System.out.println("返回值为:"+returnValue);
    }
}

实现Runnable和Callable的区别?
1,方法不同一个run一个call
2,run方法没有返回值,call方法有返回值
3,run方法没有处理异常,call方法处理异常
多线程常用方法和生命周期
常用方法
run():线程执行任务的方法(要执行任务的代码都在这方法中)
start():启动线程,最终还是调用run()。
currentThread():返回对当前正在执行的线程对象的引用。
getName():返回此线程的名称。
sleep():使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)

package com.aaa.mt.demo2;

/**
 * @FileName: SleepDemo
 * @Description:
 * @Author: zhz
 * @CreateTime: 2024/11/23 11:41
 * @Version: 1.0.0
 */
public class SleepDemo implements Runnable{
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i+"线程"+Thread.currentThread().getName()+"正在执行!!");
            try {
                //使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)
                //1秒=1000毫秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new SleepDemo()).start();
    }
}

setName("T0"):将此线程的名称更改为等于参数 name 。
setPriority():更改此线程的优先级。

package com.aaa.mt.demo2;

/**
 * @FileName: PriorityDemo
 * @Description:
 * @Author: zhz
 * @CreateTime: 2024/11/23 11:48
 * @Version: 1.0.0
 */
public class PriorityDemo implements Runnable{
    @Override
    public void run() {
        System.out.println("线程"+Thread.currentThread().getName()+"正在执行!!");
    }

    public static void main(String[] args) {
        //实例化
        PriorityDemo priorityDemo =new PriorityDemo();
        //实例化Thread
        Thread thread1 = new Thread(priorityDemo);
        Thread thread2 = new Thread(priorityDemo);
        //线程优先级 级别一共10种 数字从1-10
        // 常量3个  1=MIN_PRIORITY 5=NORM_PRIORITY 10=MAX_PRIORITY
        //优先级高的,先启动的几率大  不是一定先启动
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        //获取优先级
        System.out.println(thread1.getPriority());
        System.out.println(thread2.getPriority());
        thread1.start();
        thread2.start();
    }
}

getPriority():返回此线程的优先级。
生命周期/状态

posted on 2024-12-29 16:41  小木不痞  阅读(20)  评论(0)    收藏  举报

导航