多线程

多线程(一)

多线程的创建

方式一 继承于Thread类

1,创建一个继承于Thread类的子类
2.重写Thread类的run()
3.创建Thread类的子类的对象
4.通过此对象调用start()

方式二 :实现Runnable接口

1,创建一个实现了Runnable接口的类
2,实现类去实现Runnable中得抽象方法run();
3,创建实现类的对象
4,将次对象作为参数传递到Thread类的构造器中,创建Thread类得对象
 5,通过Thread类大的对象调用start()

比较创建线程的两种方式:

开发中 : 优先选择 :实现Runnable接口的方式
原因: 1.实现的方式没有类的单继承性的局限性
      2.实现的方式更适合来处理多个线程的共享数据的情况

 联系: public class Thread implements Runnable
相同点 : 两种方式都需要重写run(),将线程要执行的逻辑声明在run()中

方式三 :实现Callable 接口

1.创建一个实现callable的实现类
2.重写call 方法,将此线程需要执行的操作 声明在方法call()中
3.创建callable接口实现类的对象
4.将此callable接口实现类的对象传递到FutureTask构造器中,创建futureTask对象
5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()

多线程练习

package com.kuang.Demo01;

/**
 * //创建线程方式一 : 继承Thread类 ,重写run()方法,调用start开启线程
 * @author shiyu
 * @date 2021-03-31 10:31
 */
public class TestThread1 extends Thread{

    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 10; i++) {
            System.out.println("看代码");
        }
    }

    public static void main(String[] args) {
        //main线程,主线程

        //创建一个线程对象
        TestThread1 testThread1 = new TestThread1();

        //调用start() 方法开启线程
        testThread1.start();

        for (int i = 0; i < 10; i++) {
            System.out.println("主线程");
        }
    }
}
package com.kuang.Demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 练习Thread,实现多线程同步下载图片
 * @author shiyu
 * @date 2021-03-31 10:43
 */
public class TestThread2 extends Thread{
    private String url; //网络图片地址
    private String name;//保存的用户名

    public TestThread2(String url,String name){
        this.url = url;
        this.name = name;
    }
    //下载图片线程执行体
    @Override
    public void run() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downloader(url,name);
        System.out.println("下载了文件名 : " + name);
    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("https://pic.netbian.com/uploads/allimg/210328/230405-1616943845e25f.jpg","1.jpg");
        TestThread2 t2 = new TestThread2("https://pic.netbian.com/uploads/allimg/210328/225553-1616943353aca5.jpg","2.jpg");
        TestThread2 t3 = new TestThread2("https://pic.netbian.com/uploads/allimg/210328/210356-161693663629a0.jpg","3.jpg");

        t1.start();
        t2.start();
        t3.start();
    }
}
//下载器
class WebDownLoader{
    //下载方法
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader 方法出现问题");
        }
    }

}
package com.kuang.Demo01;

/**
 *创建线程方式2 :实现runnable接口 重写run 方法,执行线程需要丢入runnable接口实现类,调用start方法
 * @author shiyu
 * @date 2021-03-31 10:59
 */
public class TestThread3 implements Runnable {
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 10; i++) {
            System.out.println("看代码");
        }
    }

    public static void main(String[] args) {

        //创建runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();
        //创建线程对象,通过线程对象来开启我们的线程
        new Thread(testThread3).start();

        for (int i = 0; i < 10; i++) {
            System.out.println("主线程");
        }
    }
}
package com.kuang.Demo01;

/**
 * 多个线程同时操作一个对象
 * 买火车票的例子  : 出现线程安全问题
 * @author shiyu
 * @date 2021-03-31 11:18
 */
public class TestThread4 implements Runnable{
    private int ticketsNumber = 10;
    @Override
    public void run() {
        while(true){
            if (ticketsNumber <= 0){
                break;
            }
            //模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "----->拿了第" + ticketsNumber + "票");
        }

    }

    public static void main(String[] args) {

        TestThread4 ticket = new TestThread4();

        new Thread(ticket,"小明").start();
        new Thread(ticket,"小红").start();
        new Thread(ticket,"小绿").start();
        new Thread(ticket,"黄牛").start();
        new Thread(ticket,"黄牛").start();
    }
}

Lambda

package com.kuang.lambda;

/**
 * 推导lambda 表达式
 * @author shiyu
 * @date 2021-03-31 15:15
 */
public class TestLambda1 {
    //3.静态内部类
    static class Like2 implements ILIke{
        @Override
        public void lambda() {
            System.out.println("I like lambda2");
        }
    }
    public static void main(String[] args) {
        ILIke like = new Like();
        like.lambda();

        like = new Like2();
        like.lambda();

        //4.局部内部类
        class Like3 implements ILIke{
            @Override
            public void lambda() {
                System.out.println("I like lambda3");
            }
        }
        like = new Like3();
        like.lambda();

        //5.匿名内部类
        like = new ILIke() {
            @Override
            public void lambda() {
                System.out.println("I like lambda4");
            }
        };
        like.lambda();

        //6. 用lamada简化
        like = () -> {System.out.println("I like lambda2");};
        like.lambda();

    }


}

//1.定义一个函数时接口
interface ILIke{
    void lambda();
}

//2.实现类
class Like implements ILIke{

    @Override
    public void lambda() {
        System.out.println("I like lambda");
    }
}
package com.kuang.lambda;

/**
 * @author shiyu
 * @date 2021-03-31 15:30
 */
public class TestLambda2 {

    public static void main(String[] args) {
        ILove love = null;
        //lambda
//        ILove love = (int a) -> {
//            System.out.println(" I love you ---->" + a);
//        };
        //简化1 参数类型
        love = (a,b) -> {
            System.out.println(" I love you ---->" + a);
            System.out.println(" I love you ---->" + b);
        };
        //简化2 简化括号
//        love = a -> {
//            System.out.println(" I love you ---->" + a);
//        };
        //简化3 简化花括号
        //love = a -> System.out.println(" I love you ---->" + a);

        //总结
          //lambda表达式只有一行的代码的情况下才可以简化为一行,如果多行,就用代码块包裹
          // 前多个参数也可以去掉参数类型,要去去掉就都去掉

        love.love(521,502);

    }
}

interface ILove{
    void love(int a,int b);
}

多线程方法

package com.kuang.state;

/**
 * @author shiyu
 * @date 2021-03-31 16:53
 */
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 < 36500 ; i++) {
            System.out.println("你一生都开心的活着");
        }
        System.out.println(" goodbye World ");
    }
}
package com.kuang.state;

/**
 * 测试join 插队 
 * @author shiyu
 * @date 2021-03-31 16:21
 */
public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 1000 ; i++) {
            System.out.println("VIP 来了" + i);
            
        }
    }
    public static void main(String[] args) throws InterruptedException {

        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 500; i++) {
            if (i== 200){
                thread.join();
            }
            System.out.println("main" + i );

        }

    }
}
package com.kuang.state;

/**
 * @author shiyu
 * @date 2021-03-31 16:42
 */
public class TestPriority {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.start();

        t4.setPriority(4);
        t4.start();

        t5.setPriority(Thread.MAX_PRIORITY);
        t5.start();

        t6.setPriority(7);
        t6.start();


    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
    }
}
package com.kuang.state;

import com.kuang.Demo01.TestThread4;

/**
 * @author shiyu
 * @date 2021-03-31 16:05
 */
public class TestSleep implements Runnable{
    private int ticketsNumber = 10;
    @Override
    public void run() {
        while(true){
            if (ticketsNumber <= 0){
                break;
            }
            //模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "----->拿了第" + ticketsNumber + "票");
        }

    }

    public static void main(String[] args) {

        TestThread4 ticket = new TestThread4();

        new Thread(ticket,"小明").start();
        new Thread(ticket,"小红").start();
        new Thread(ticket,"小绿").start();
        new Thread(ticket,"黄牛").start();
        new Thread(ticket,"黄牛").start();
    }
}
package com.kuang.state;

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

/**
 * 模拟倒计时
 * @author shiyu
 * @date 2021-03-31 16:07
 */
public class TestSleep2 {
    public static void main(String[] args) {
//        try {
//            tenDown();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //打印当前系统时间
        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();
            }
        }
    }
    //模拟倒计时
    public static void tenDown() throws InterruptedException{
        int num = 10;
        while(true){
            Thread.sleep(100);
            System.out.println(num--);
            if (num < 0){
                break;
            }
        }
    }
}
package com.kuang.state;

/**
 * 测试线程的状态
 * @author shiyu
 * @date 2021-03-31 16:28
 */
public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } 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(state != Thread.State.TERMINATED){//只要线程不终止,就一直输出
            Thread.sleep(1000);
            state = thread.getState();//更新线程状态
            System.out.println(state);//输出状态

        }
    }
}
package com.kuang.state;

/**
 * 测试Stop
 * 1.建议线程正常停止---->利用次数 ,不建议死循环
 * 2.建议使用标志位----> 设置一个标志位
 * 3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
 * @author shiyu
 * @date 2021-03-31 15:53
 */
public class TestStop implements Runnable {

    //1.设置一个标识位
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("run......Thread" + i++);
        }
    }
    //2.设置一个公开的方法停止线程
    public void stop(){
        this.flag = false;
    }

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

        for (int i = 0; i < 1000; i++) {
            System.out.println("main" + i);
            if (i == 900){
                //调用stop方法切换标志位 ,让线程停止
                testStop.stop();
                System.out.println("线程该停止了");
            }

        }
    }
}
package com.kuang.state;

/**
 * 测试礼让线程
 * @author shiyu
 * @date 2021-03-31 16:16
 */
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }
}
class MyYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + "线程停止执行");
    }
}

线程不安全示例

package com.kuang.syn;

/**
 *不安全的取钱
 * 两个人与银行取钱
 * @author shiyu
 * @date 2021-03-31 18:00
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "基金");
        Drawing you = new Drawing(account, 50, "你");
        Drawing girlFriend= new Drawing(account, 100, "girlFriend");
        you.start();
        girlFriend.start();

    }
}
//账户
class Account{
    int money; //余额
    String name;//卡名
    public Account(int money ,String name){
        this.money = money;
        this.name = name;
    }
}
//银行 模拟取款
class Drawing extends Thread{
    Account acct;
    int drawingMoney;
    int nowMoney;
    public Drawing(Account acct,int drawingMoney,String name){
        super(name);
        this.acct = acct;
        this.drawingMoney = drawingMoney;

    }
    //取钱
    @Override
    public void run() {
        //判断有钱没钱
        if (acct.money - drawingMoney < 0) {
            System.out.println("钱不够,取不了");
            return;
        }
        //sleep 放大问题的发生性
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //卡内余额
        acct.money = acct.money - drawingMoney;
        //手里的钱
        nowMoney = nowMoney + drawingMoney;
        System.out.println(acct.name + "余额为:" + acct.money);
        System.out.println(this.getName() + "手里的钱 : " + nowMoney);
    }
}
package com.kuang.syn;

/**
 * 不安全的买票
 * 有负数
 * @author shiyu
 * @date 2021-03-31 17:52
 */
public class UnsafeBuyticket {
    public static void main(String[] args) {
        Buyticket buyticket = new Buyticket();

        new Thread(buyticket,"我").start();
        new Thread(buyticket,"你").start();
        new Thread(buyticket,"黄牛").start();
    }

}
class Buyticket implements Runnable{

    private int ticketNum = 10;
    boolean flag = true;
    @Override
    public void run() {
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNum <= 0){
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNum--);
    }
}
package com.kuang.syn;

import java.util.ArrayList;

/**
 * 线程不安全集合
 * @author shiyu
 * @date 2021-03-31 17:43
 */
public class UnsafeList {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {//添加用线程
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.size());

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值