多线程

继承Thread类

public class Thread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("执行多线程方法");
        }
    }
}
class Main{
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("执行主线程方法");
        }
    }
}

实现Runnable接口

public class Thread1 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("执行多线程方法");
        }
    }
}
class Main{
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        new Thread(thread1).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("执行主线程方法");
        }
    }
}

实现Callable接口

import java.util.concurrent.*;

public class Thread1 implements Callable<Boolean> {
    @Override
    public Boolean call(){
        for (int i = 0; i < 20; i++) {
            System.out.println("执行线程方法");
        }
        return true;
    }
}
class Main{
    public static void main(String[] args) {
        /**
         * 第一种启动方式
         */
        /*Thread1 thread1 = new Thread1();
        ExecutorService ser = Executors.newFixedThreadPool(3);
        Future r1 = ser.submit(thread1);
        for (int i = 0; i < 20; i++) {
            System.out.println("执行主线程方法");
        }
        ser.shutdownNow();*/

        /**
         * 第二种启动方式
         */
        FutureTask<Boolean> futureTask = new FutureTask(new Thread1());
        new Thread(futureTask).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("执行主线程方法");
        }
        try {
            Boolean a = futureTask.get();
            System.out.println(a);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

龟兔赛跑(线程Demo)

public class Race implements Runnable{
    private String winner;
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if(Thread.currentThread().getName().equals("兔子")&&(i%10==0)){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag = gameover(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }
    }
    //判断是否完成比赛
    private boolean gameover(int steps){
        if (winner!=null){//胜利者出现
            return true;
        }{
            if (steps>=100){
                winner = Thread.currentThread().getName();
                System.out.println("winner is"+winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

Lamda 表达式

public class Race {
    public static void main(String[] args) {
        //未简化前
        /*Test test = (a) -> {
            System.out.println(a);
        };
        test.method(520);*/
        //简化后
        Test test = a-> System.out.println(a);
        test.method(520);
        /*
        lamda表达式只有一行代码的情况下才能去掉花括号,多行需要花括号包裹
        lamda前提必须是函数式接口
        多个参数可以去掉参数类型,要去都去,但必须加上括号
        */
    }
}
interface Test{
    void method(int a);
}

线程停止(设立标志位,用flag控制线程关闭)

public class Thread2 implements Runnable{
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("运行"+i++);
        }
    }
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        Thread2 thread2 = new Thread2();
        new Thread(thread2).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("主线程运行"+i);
            if(i==900){
                thread2.stop();
                System.out.println("线程停止了");
            }
        }
    }
}

线程休眠(计时器)

import java.text.SimpleDateFormat;
import java.util.Date;

public class Sleep {
    public static void main(String[] args) {
        Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime = new Date(System.currentTimeMillis());//更新
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

ArrayList线程不安全演示

public class Sleep {
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}

ReentrantLock

import java.util.concurrent.locks.ReentrantLock;

public class Lock {
    public static void main(String[] args) {
        Lock1 lock1 = new Lock1();
        new Thread(lock1).start();
        new Thread(lock1).start();
        new Thread(lock1).start();
    }
}
class Lock1 implements Runnable{
    private int ticketNum = 10;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if (ticketNum>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNum--);
                }else{
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

创建线程池

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

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService exr = Executors.newFixedThreadPool(4);
        exr.execute(new MyThread());
        exr.execute(new MyThread());
        exr.execute(new MyThread());
        exr.execute(new MyThread());
    }
}
class MyThread implements Runnable{

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

-----参考b站up主:遇见狂神说

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值