JAVA高级应用之线程续写

线程应用

示例1

公司年会 进入公司有两个门(前门和后门)
进门的时候 每位人都能获取一张彩票(7位数)
公司有100个员工
利用多线程模拟进门过程
统计每个入口入场的人数 
每个人拿到的彩票的号码 要求7位数字 不能重复
打印格式:
编号为: 1 的员工 从后门 入场! 拿到的双色球彩票号码是: [17, 24, 29, 30, 31, 32, 07]
编号为: 2 的员工 从后门 入场! 拿到的双色球彩票号码是: [06, 11, 14, 22, 29, 32, 15]
.....
从后门 入场的员工总共: 45 位员工
从前门 入场的员工总共: 55 位员工
package com.lanou3g;

import java.awt.List;
import java.util.ArrayList;

public class Demo01 {
    public static void main(String[] args) {
        // 创建线程
        YHRunnable runnable = new YHRunnable();
        Thread t1 = new Thread(runnable, "前门");
        Thread t2 = new Thread(runnable, "后门");
        t1.start();
        t2.start();
    }
}

class YHRunnable implements Runnable{
    // 操作的共享数据 100人
    private int pNum = 100;
    // 记录从前门入门的人数
    private int qNym = 0;
    // 记录从后门入门的人数
    private int hNum = 0;
    @Override
    public void run() {
        // 进门
        while(true) {
            // 添加同步锁
            synchronized (this) {

            // 结束循环条件
            if(pNum <= 0) {
                break;
            }
            // 获取进入的线程的名字
            String name = Thread.currentThread().getName();
            // 前门进
            if(name.equals("前门")) {
                // 记录前门进的人数
                qNym++;
                System.out.print("编号为:" + (100 - pNum + 1) + 
                        "从" + name + "入场!" + "拿到的双号球彩票号码是:");
                printCP();
                pNum--;
            }
            // 后门进
            if(name.equals("后门")) {
                hNum++;
                System.out.print("编号为:" + (100 - pNum + 1) + 
                        "从" + name + "入场!" + "拿到的双号球彩票号码是:");
                printCP();
                pNum--;
            }
            // 人数等于0了 打印 前后门进了多少
            if(pNum == 0) {
                System.out.println("从前门" + "入场的员工总数:" +qNym);
                System.out.println("从后门" + "入场的员工总数:" +hNum);
            }
        }
            Thread.yield();
        }
    }
    // 打印彩票号的方法
    public void printCP() {
        ArrayList<Integer> list = new ArrayList<>();
        // 循环添加到数组中
        while(list.size() < 7) {
            // 随机数
            int num = (int)(Math.random()*(30 - 1 + 1) + 1);
            // 添加进去数组中
            if(!list.contains(num)) {
                list.add(num);
            }
        }
        // 打印
        System.out.println(list);
    }
}
需要一份共享的数据,实现两个线程同时使用这份数据,因此只能创建一个对象,由两个线程共享,如果有两份数据
由两个线程分别使用,则将毫无意义,先分析清楚需要哪些步骤,后编写代码

停止线程

停止线程:只要线程停了就叫停止线程
具体有两种实现方式
一种是使用bool标记的方式
另一种是使用interrupt中断线程

测试结果:interrupt是不能结束字子线程的
实际上这个interrupt()方法
设置了isInterrupted 布尔值

如果线程中有wait()等待 或者 sleep休眠
这时调用interrupt()方法
会抛出一个异常IntterruptedException
并且清楚中断状态

如果线程中没有等待或者休眠
这时调用interrupt方法
会设置中断状态(true/false的改变)
中断了线程
package com.lanou3g;

public class Demo20 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        thread.interrupt();
        System.out.println("线程已经中断了");
        System.out.println(Thread.currentThread().getName());
        System.out.println("主线程结束了");
    }
}
class MyRunnable implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(!Thread.currentThread().isInterrupted()) {
            long millis = System.currentTimeMillis();
            while (System.currentTimeMillis() - millis < 1000) {        
            }
            System.out.println(Thread.currentThread().getName());
        }
    }

}
未中断线程
package com.lanou3g;

public class Demo21 {
    public static void main(String[] args) {
        MyRunnable3 myRunnable3 = new MyRunnable3();
        Thread thread = new Thread(myRunnable3);
        thread.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        thread.interrupt();
        System.out.println("线程已经终止了");
        System.out.println(Thread.currentThread().getName());
        System.out.println("主线程已经停止");
    }
}
class MyRunnable3 implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }

}

测试中断状态

注意:interrupt方法 尽量不要使用
如果要停止线程 直接使用标记法
只有遇到了 冷冻状态时 可以使用该方法

IllegalMonitorStateException
对象监视器 就是对象锁
wait方法是Object类
wait方法必须使用锁对象去调用
线程等待 放弃了cup的执行资源
package com.lanou3g;

public class Demo23 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        t1.start();
        t2.start();

        for (int i = 0; i < 50; i++) {
            if(i == 25) {
                t1.interrupt();
                t2.interrupt();
            }
            System.out.println(i + "------ ");
        }
        System.out.println("主线程结束");
    }
}
class MyThread extends Thread{
    @Override
    public synchronized void run() {
        // TODO Auto-generated method stub
        while(true) {
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " ");
        }
    }
}
线程1进来了 带着锁 遇到wait()方法
放弃了cpu的执行权 但是锁会还回去
线程2进来了 又遇到了等待了
相当于我的两个线程 都跟这里等着了
进入冷冻(中断)状态
解除冷冻(中断)状态
调用interrupt清楚该状态

代码示例

/*
 * Person类 姓名 性别
 * 开启两个线程
 * 一个对Person对象进行赋值
 * 一个对Person对象进行打印
 * 要求
 * 一次打印 丁鹏 男
 * 一次打印 dingpeng nv
 * 间隔输出
 * 
 * 1.先保证要操作的是同一个对象
 * 2.要保证数据安全需要使用锁,并且要使用同一把锁
 * 3.保证操作的逻辑顺序要对(先赋值,在打印)用 wait 和 notify
 */
package com.lanou3g;

public class Demo06 {
    public static void main(String[] args) {
        // 创建对象(只能使用同一个对象)
        Person person = new Person();

        // 创建线程
        SetRunnable setRunnable = new SetRunnable(person);
        Thread thread1 = new Thread(setRunnable);

        PrintRunnable printRunnable = new PrintRunnable(person);
        Thread thread2 = new Thread(printRunnable);

        thread1.start();
        thread2.start();
    }
}
// 赋值线程
class SetRunnable implements Runnable {
    // 利用成员变量,来操作同一个对象
    private Person person;
    // 定义一个标识通过改变标识来进行间隔赋值
    private boolean isTrue = true;
    // 利用构造方法来给成员变量赋值
    public SetRunnable() {
        super();
    }
    public SetRunnable(Person person) {
        super();
        this.person = person;
    }

    @Override
    public void run() {
        while (true) {
            // 多个线程操作共享数据
            // 需要添加锁
            // 为了保证两个同步锁的锁对象相同,使用传进来的对象 person
            /*
             * 赋值线程需要赋值完毕,打印线程才能去打印
             * 赋值时,打印线程等待,赋值完毕后,通知打印线程,打印线程才能打印
             * 
             * 同样,打印线程打印完毕,赋值线程才能赋值
             * 打印时,赋值线程等待,打印完毕后,通知赋值线程,赋值线程才能赋值
             * 
             * wait 和 notify 使用一个标记来进行切换
             * 这个标记赋值线程使用,也要给打印线程使用
             * 注意:必须保证使用的是用一个标记,标记声明在 person 类中,即声明在共同对象中
             * 
             */
            synchronized (person) {
                // 判断 flag 为 true 时等待,不为 true 时赋值
                if (person.flag == true) {
                    // 进行等待
                    try {
                        person.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 间隔赋值
                if (isTrue) {
                    person.name = "张三";
                    person.gender = "男";
                } else {
                    person.name = "zhangsan";
                    person.gender = "nv";
                }
                // 改变标识符
                isTrue = !isTrue;
                // 修改标记
                person.flag = true;
                // 唤醒线程
                person.notify();
            }
        }
    }
}
// 打印线程
class PrintRunnable implements Runnable {
    // 利用成员变量,来操作同一个对象
    private Person person;
    public PrintRunnable() {
        super();
    }
    public PrintRunnable(Person person) {
        super();
        this.person = person;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (person) {
                if (person.flag == false) {
                    try {
                        person.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
//              try {
//                  Thread.sleep(1000);
//              } catch (InterruptedException e) {
//                  // TODO Auto-generated catch block
//                  e.printStackTrace();
//              }
                // 打印
                System.out.println(person);
                // 修改标记
                person.flag = false;
                // 唤醒线程
                person.notify();
            }
        }
    }
}
class Person {
    public String name;
    public String gender;
    // 声明标记来切换打印和赋值
    public boolean flag = false;
    @Override
    public String toString() {
        return "姓名:" + name + "\n年龄:" + gender;
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值