多线程的学习

视频学习请参考:https://www.bilibili.com/video/BV1V4411p7EF?p=3&spm_id_from=pageDriver

理解程序、进程、线程的概念
        程序可以理解为静态的代码
        进程可以理解为执行中的程序。
        线程可以理解为进程的进一步细分,程序的一条执行路径

1、实现方式1-继承Thread类

package com.xuexi.thread;

public class TestThread01 extends  Thread {


    // 一定要重写相应的run方法。
    @Override
    public void run() {
        // 方法的线程体
        for(int i = 0; i<200;i++){
            System.out.println("这里是一个方法线程");
        }

    }

    public static void main(String[] args) {

        TestThread01 testThread01 = new TestThread01();

        // 这样调用的话是日常调用方法的方法。
        // testThread01.run();
        // 会开启另外一个线程
        testThread01.start();

        // 主线程
        for(int i = 0; i < 2000; i++){
            System.out.println("这里是一个主线程");
        }

    }



}

2、实现方式2-实现接口Runnable

package com.xuexi.thread;

public class TestThread02 implements Runnable {

    @Override
    public void run() {
        // 方法的线程体
        for(int i = 0; i<200;i++){
            System.out.println("这里是一个方法线程");
        }

    }

    public static void main(String[] args) {

        // 创建Runnable接口的实现类对象
        TestThread02 testThread02 = new TestThread02();

        // 创建线程对象,通过线程对象来开启我们的线程,代理
        new Thread(testThread02).start();
        // 主线程
        for(int i = 0; i < 2000; i++){
            System.out.println("这里是一个主线程");
        }

    }


}

3、插一条编程方式(lambda编程)

package com.xuexi.thread;


// jdk1.8 的新特性,接口函数编程
public class Lambda {

    public static void main(String[] args) {
        // 函数编程(方式一)
        Ilove love  = (int a)->{
            System.out.println("woain"+a);
        };
        love.happy(520);


        // 简化1-参数的类型省略
        Ilove love2  = (a)->{
            System.out.println("woain"+a);
        };
        love2.happy(520);

        // 简化2-小括号的省略
        Ilove love3  = a->{
            System.out.println("woain"+a);
        };
        love3.happy(520);

        // 简化3-花号的省略
        Ilove love4  = a->System.out.println("woain"+a);

        love4.happy(520);

        /**
         * 总结一下:
         * 1.这种lambda形式的编程,其接口内只能有一个方法。
         * 2.省略参数的类型的话,如果省略其中一个,则其他的也必须都省略,同时不能去掉从参数的小括号
         * 3.简化三这种,花括号的省略,只能在里面只有一行语句的时候省略。
         */


    }
}


interface Ilove{
    public void happy(int a);
}




4、线程相关信息

4.1、 线程的状态

4.2、线程的方法

4.3 、线程的停止

  

package com.xuexi.state;


import com.xuexi.thread.TestThread02;
import sun.applet.Main;
import sun.font.TrueTypeFont;

// 线程的停止,这里一般使用两种方法进行停止
// 1.设置循环次数,有限次数;
// 2.使用标志位-flag
public class TestStop implements Runnable {
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            System.out.println("我在执行");
        }

    }

    public void stop(boolean flag) {
        this.flag = flag;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();

        for (int i = 0; i < 100; i++) {
            System.out.println("main");
            if(i==80){
                testStop.stop(false);
                System.out.println("停止了");

            }
        }
    }
}

  4.4、线程的休眠

package com.xuexi.state;

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

public class TestSleep
{

    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();
            }
        }
    }


}

4.5、线程礼让(了解)

4.6、Join

package com.xuexi.state;

public class TestJion implements Runnable {


    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("插队线程"+i);
        }

    }

    public static void main(String[] args) throws InterruptedException {
        // 主线程
        TestJion testJion = new TestJion();
        Thread thread = new Thread(testJion);
        thread.start();

        for (int i = 0; i < 200; i++) {
            if (i == 100) {
                thread.join();
            }
            System.out.println("mian"+i);
        }
    }
}

4.7、线程状态的观测

package com.xuexi.state;

public class TestState {
    public static void main(String[] args) throws InterruptedException {
        // 线程体,因为其继承了Runnable接口,且接口内只有一方法
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("结束");

        });

        // 观察状态
        Thread.State state = thread.getState();
        System.out.println(state);

        // 启动状态
        thread.start();
        state = thread.getState();
        System.out.println(state);


        while (thread.getState() != Thread.State.TERMINATED) {
            Thread.sleep(100);

            state = thread.getState();
            System.out.println(state);

        }



    }


}

 4.8、线程的优先级(了解,一般不用设置)

 4.9、守护线程

package com.xuexi.state;

import sun.font.TrueTypeFont;

// 测试守护线程
public class TestDaemon {
    public static void main(String[] args) {

        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true);//默認為false
        thread.start();

        new Thread(you).start();



    }
}


class God implements Runnable{


    @Override
    public void run() {
        while(true){
            System.out.println("守護你");

        }
    }
}
class You implements Runnable{


    @Override
    public void run() {
        for (int i = 0; i < 66; i++) {
            System.out.println("happy");
        }
        System.out.println("over");

    }
}

 5、线程同步

 

  

 

 

 

设置同步方法

package com.xuexi.syn;

public class TestSynchronized {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"zhangsan").start();
        new Thread(buyTicket,"lisi").start();
        new Thread(buyTicket,"wangwu").start();
    }
}

class BuyTicket implements Runnable{
    private int ticketNum = 10;
    private boolean flag = true;// 外部设置的停止方法

    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized 设置为同步方法
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        // 延时
        Thread.sleep(100);
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
    }
}

设置同步代码块

6、死锁

 扩展

 

  7、线程通信

 

8、线程池

   

package com.xuexi.syn;

import javax.xml.ws.Service;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestPool {

    public static void main(String[] args) {
        // 创建服务,创建线程池子
        ExecutorService service = Executors.newFixedThreadPool(50);

        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        // 关闭连接
        service.shutdown();



    }


}

class MyThread implements Runnable{


    @Override
    public void run() {

        for (int i = 0; i < 1; i++) {
            System.out.println(Thread.currentThread().getName()+i);
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值