线程基础代码总结

线程代码总结

1.线程创建第一种方式(继承Thread类)重写run方法

下划线代表新的类,可自行创建

public class Demo01Thread {
    public static void main(String[] args) {
        MyThread m = new MyThread();
        m.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main"+i);
        }
    }
}
------------------------------
public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("run:"+i);
        }
    }
}

线程的sleep方法

public class Demo4 {
    public static void main(String[] args) {
        //模拟秒表
        for (int i = 1; i <= 60; i++) {
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
2.线程创建第二种方式(实现Runnable接口)重写run方法实现Runnable接口的好处:

实现Runnable接口的好处

  • 1.避免了单继承的局限性 实现了Runnable接口 还可以实现其他接口
  • 2.增强了程序的扩展性 降低了耦合性
    把设置线程任务和开启新线程进行了分离 可以传递不同的实现类,就可以执行不同的线程任务
public class Demo5 {
    public static void main(String[] args) {
        Runnable run = new MyThread5();
        Thread t = new Thread(run);
        t.start();
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"-->"+i);
        }
    }
}
--------------------------------------
public class MyThread5 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"-->"+i);
        }
    }
}

补充:start()和run()的区别

  • run():Thread本身也是实现Runnable接口。Runnable接口只有一个方法就是run方法。启动线程时,会使得run方法在那个独立执行的线程中被调用;run方法的内容就是线程任务也称为线程体
  • start():start方法就是启动线程,会导致run方法的调用。
  • 使用start方法,是真的启动了线程,达到了异步执行的效果。而使用run方法并没有真的启动线程,而是由main线程去调用run方法,还是在main线程里执行。

匿名内部类实现线程的创建(函数式编程也可以)

public class Demo6 {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 20; i++) {
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        });
        t.start();
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"-->"+i);
        }
    }
}
3.由多线程引出的线程安全问题:多线程访问共享数据,就会产生经典的卖票问题(出现0、-1或者同时出现100)

解决:解决:保证同一时间只有一个线程在操作共享数据。即线程同步技术

3.1同步代码块(推荐使用)
public class RunnableImpl implements Runnable{
    //定义一个多个线程共享的票源
    private int ticket = 100;

    //创建一个锁对象  保证其唯一性
    Object o = new Object();
    @Override
    public void run() {
        while (true){
            //创建一个同步代码块
            synchronized (o){
                if(ticket>0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"-->正在卖第"+ticket+"张票");
                    ticket--;
                }
            }
        }
    }
}
--------------------------------
public class Temo4 {
    public static void main(String[] args) {
        Runnable run = new RunnableImpl();
        Thread t = new Thread(run);
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);
        t.start();
        t1.start();
        t2.start();
    }
}

过程解释:
t抢到了CPU执行权,执行run方法,遇到synchronized代码块,此时t检查synchronized代码块是否有锁对象,发现有,就会获取锁对象,进入同步执行;t2抢到了CPU执行权,执行run方法,遇到synchronized代码块,此时t2检查synchronized代码块是否有锁对象,发现没有,t2进入阻塞状态,会一直等待t归还锁对象,一直到t执行完同步代码块,把锁对象归还给同步代码块,此时t2获得锁对象,进入同步代码块执行。
同步中的线程,没有执行完毕不会释放锁,同步外的线程没有锁进不去同步

3.2同步方法
public class RunnableImpl implements Runnable{
    //定义一个多个线程共享的票源
    private int ticket = 100;

    //创建一个锁对象  保证其唯一性
    Object o = new Object();
    @Override
    public void run() {
        payTicket();
    }
    /*
    定义一个同步方法
     */
    public synchronized void payTicket() {
        while (true){
            //创建一个同步代码块
            synchronized (o){
                if(ticket>0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"-->正在卖第"+ticket+"张票");
                    ticket--;
                }
            }
        }
    }
}
----------------------------------
public class Temo5 {
    public static void main(String[] args) {
        Runnable run = new RunnableImpl();
        Thread t = new Thread(run);
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);
        t.start();
        t1.start();
        t2.start();
    }
}
3.Lock锁
public class RunnableImpl implements Runnable{
    //1.在成员位置创建一个ReentrantLock对象
    Lock l = new ReentrantLock();
    private int ticket = 100;

    @Override
    public void run() {
        while (true){
            //2.在可能出现安全问题的代码前调用lock方法获取lock锁
            l.lock();
                if(ticket>0) {
                    try {
                        Thread.sleep(10);
                        System.out.println(Thread.currentThread().getName()+"-->正在卖第"+ticket+"张票");
                        ticket--;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        //3.在可能出现安全问题的代码后释放lock方法获取lock锁
                        //无论程序是否异常 都释放锁
                        l.unlock();
                    }
                }
        }
    }
}
---------------------------------
public class Demo1 {
    public static void main(String[] args) {
        Runnable run = new RunnableImpl();
        Thread t = new Thread(run);
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);
        t.start();
        t1.start();
        t2.start();
    }
}
4.线程通信

概念:多个线程在处理同一资源,但是各自线程的任务却不相同,所以存在线程通信
wait()和notify()必须由同一个锁对象调用(重点)
notify()和wait()必须在同步代码块或同步函数中使用(重点)

4.1示例 包子问题

Step1:创建一个资源类

public class BaoZi {
    String pi;
    String xian;
   //flag表示是否有包子
    boolean flag = false;
}

Step2:创建包子铺线程类

/*
使用包子对象作为锁对象
 */
public class BaoZiPu extends Thread{
    private BaoZi bz;
    public BaoZiPu(BaoZi bz) {
        this.bz = bz;
    }
    //线程任务 生产包子
    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (bz) {
            if (bz.flag==true) {
                try {
                    //有包子,包子铺线程等待
                    bz.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //被唤醒之后执行,包子铺生产包子  生产两种包子 根据count% 2==0的结果
            if(count%2==0) {
                bz.pi = "薄皮";
                bz.xian = "三鲜";
            }else {
                bz.pi = "冰皮";
                bz.xian = "牛肉";
            }
            count++;
            System.out.println("包子铺正在生产"+bz.pi+bz.xian+"包子");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            bz.flag=true;
            //唤醒吃货线程
            bz.notify();
            System.out.println("包子铺已经生产"+bz.pi+bz.xian+"包子,可以开始吃了");
        }}

    }
}

Step3:创建吃货线程类

public class ChiHuo extends Thread{
    private BaoZi bz;
    public ChiHuo(BaoZi bz) {
        this.bz = bz;
    }
    @Override
    public void run() {
        while (true) {
            synchronized (bz) {
                if(bz.flag==false){
                    try {
                        bz.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //被唤醒之后执行的代码
                System.out.println("吃货正在吃:"+bz.pi+bz.xian+"的包子");
                bz.flag=false;
                bz.notify();
                System.out.println("吃货已经吃完了:"+bz.pi+bz.xian+"的包子"+"...包子铺开始生产包子");
            }
        }
    }
}

Step4:测试类

public class Demo {
    public static void main(String[] args) {
        BaoZi bz = new BaoZi();
        //开启包子铺线程 生产包子
        new BaoZiPu(bz).start();
        //开启吃货线程,吃包子
        new ChiHuo(bz).start();
    }
}

运行结果截图:
在这里插入图片描述

5.线程池

Executor 线程池的工厂类 用来生成线程池

submit(Runnable task)提交一个Runnable任务用于执行
void shutdown() 关闭销毁线程池的方法
使用步骤
1:使用静态方法newFixedThreadPool生成一个指定线程数量的线程池
2:创建一个类,实现Runnable接口,重写run方法,设置线程任务
3:调用ExecutorService的方法submit,传递线程任务,开启线程,执行run方法
4:调用ExecutorService的方法shutdown,销毁线程池(不建议执行)

public class Demo1 {
   public static void main(String[] args) {
       //1.
       ExecutorService es = Executors.newFixedThreadPool(2);
       //3.
       es.submit(new RunnableImpl());
       es.submit(new RunnableImpl());
       es.shutdown();
   }
}
-----------
//2.
public class RunnableImpl implements Runnable{
   @Override
   public void run() {
       System.out.println(Thread.currentThread().getName()+"创建了一个新的线程执行");
   }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值