多线程基础学习

多线程 java.Thread

  1. 描述

    1. 多任务
    2. 多线程
      • CPU调度的单位
      • 独立执行路径
      • Main 主线程
      • 资源抢夺 并非控制
      • 额外开销
      • 自己内存交互 数据不一样
      • 优先权
    3. 进程(Process)
      • 程式执行过程
      • 包含多个线程
      • 系统分配资源
  2. 实现

    1. 线程的创建

      • Thread 类

        //创建线程方式一
        public class TestThread extends Thread{
            public void run(){
                //run方法线程
                for (int i = 0; i < 20; i++){
                    System.out.println("我在看代码!")
                }
            }
            
            public static void main(String[] args){
              //main主线程
                
                //创建一个线程对象
                TestThread testT = new TestThread();
                
                //调用start() 开启线程
                testT.start();
                for (int i = 0; i < 20; i++){
                    System.out.println("我在学习代码!")
                }
            }
        }
        
        总结:线程开始 不一定会立即执行 由CPU调度执行
        

        案例

        import org.apache.commons.io.FileUrils;
        
        //练习Thread , 实现多线程同步下载图片
        public class TestThread2 extends Thread{
            private String url;  //网络图片地址
            private String name; //保存图片名字
            
            public TestThread2(String url,String name){
                this.url = url;
                this.name = name;
            }
            
            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(url,name);
                TestThread2 t2 = new TestThread2(url1,name);
                TestThread2 t3 = new TestThread2(url2,name);
                
                //执行
                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方法出现错误!")
                }
            }
        }
        
      • Runnable接口

        //通过实现Runnable接口创建线程
        public class TestThread3 implements Runnable{
            public void run(){
                //run方法体
                for(int i = 0; i < 20; i++){
                    System.out.println("在看代码!")
                }
            }
            
            public static void main(String[] args){
                //创建接口实现类
                TestThread3 t1 = new TestThread3();
                
                //创建线程对象
                //把接口实现类作为target传给线程对象
                Thread t2 = new Thread(t1);
                t1.start();
                
                for(int i = 0;i < 20; i++){
                    System.out.println("在学习代码!")
                }
            }
        }
        
        推荐使用:避免单继承局限性,灵活方便
        

        实列

        //多个线程同时操作同一个对象
        //问题:多线程同时开启 数据不安全 数据不对 
        public class TestThread4 implements Runnable {
            
            private int ticketNums = 10;
            
            public void run(){
                while(true){
                    if(ticketNums<=0){
                        break;
                    }
                    //模拟延时
                    try {
                        Thread.sleep(200);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"--->拿到了"+ticketNums-- +"---票");
                }
            }
            
            public static void main(String[] args){
                TestThread4 ticket = new TestThread4();
                
                new Thread(ticket,"老师").start();
                new Thread(ticket,"学生").start();
                new Thread(ticket,"黄牛党").start();
            }
        }
        
      • Callable接口

  3. 状态

    • 线程状态监听

      //监听
      public class TestState {
          public static void main(String[] args){
              //线程
              Thread thread = new Thread(()->{
                  for(int i = 0; i < 5; i++){
                      try {
                          Thread,sleep(1000);
                      }catch(InterruptedException i){
                          i.printStackTrace();
                      }
                  }
                  System.out.println("线程结束========");
              });
              
              //获取状态
              Thread.state state = thread.getState();
              System.out.println(state);
              
              thread.start();
              
              //start()后状态
              state = thread.getState();
              
              while(state != Thread.getState.TERMINATED){//TERMINATED 死亡
                  Thread.sleep(100);
                  state = thread.getState();
                  System.out.println(state);
              }
              
              //thread.start(); 死亡后不能在调用
              //throw IllegalThreadStateException
          }
      }
      
    • 创建

    • 就绪

      • 线程礼让 yield

        • 让线程转为就绪状态

          //礼让不一定成功 看CPU
          public class TestYield {
              MyYield yield = new MyYield();
              new Thread(yield,"a").start();
              new Thread(yield,"b").start();
          }
          
          class MyYield implements Runnable {
              public void run(){
                  System.out.println(Thread.currentThread().getName()+"线程开始执行");
                  //线程礼让
                  Thread.yield();
                  System.out.println(Thread.currentThread().getName()+"线程执行结束")
              }
          }
          
          
    • 运行

    • 阻塞

      • 线程sleep

        • 指定线程阻塞时间(毫秒)

        • 存在异常InterruptedException

        • 解除阻塞后进入就绪

        • 模拟网络延时 到计时

          //模拟网络延时:放大问题的发生性
          pbulic class TestSleep implements Runnable {}
          

          实列2

          //模拟倒计时
          public class TestSleep2 {
              public static void mian(String[] args){
                  //获取当前系统时间
                  Date startTime = new Date(System.currentTimeMillis());
                  try {
                      while(true){
                          Thread.sleep(1000);
                          System.out.println(new SimpleDateFormat("HH:MM:SS").format(startTime));
                          //更新时间
                          startTime = new Date(System.currentTimeMillis());
                      }
                  }
                  
                 
                  try{
                      tenDown();
                  }catch(InterruptedException i){
                      i.printStackTrace();
                  }
              }
              public void tenDown() throws InterruptedException {
                  int num = 10;
                  while(true){
                      Thread.sleep(1000);
                      System.out.println(num--);
                      if(num<=0){
                          break;
                      }
                  }
              }
          }
          
          • 阻塞join

            public class TestJoin implements Runnable {
                
                public void run(){
                    for(int i = 0; i < 50; i++){
                        System.out.println("线程vip来了"+i);
                    }
                }
                
                public static void main(String[] args){
                    TestJoin tj = new TestJoin();
                    new Thread(tj).start();
                    
                    for(int i = 0; i < 2000; i++){
                        System.out.println("main"+i);
                        if(i==200){
                            //插队线程 其他线阻塞
                            tj.join();
                        }
                    }
                }
            }
            
        • 不释放对象锁

    • 死亡

      • 线程stop
      //测试stop
      //1.建议线程正常停止---》利用次数,不建议循环
      //2.建议使用标志位----》设置标注位
      //3.不要使用stop或者destroy等过时或JDK不建议使用的方式
      
      public class TestStop implements Runnable {
          
          //设置一个标志位
          private boolean flag = true;
          
          public void run(){
              int i = 0;
              while(flag){
                  System.out.println("run......Thread"+i++);
              }
          }
         
          //该方法公开用来切换标志位 线程停止
          public void stop(){
              this.flag = false;
          }
          
          public static void main(String[] args){
              TestStop t = new TestStop();
              new Thread(t).start();
              
              for(int i = 0; i < 200; i++){
                  System.out.println("main------"+i);
                  if(i==100){
                      //调用stop切换标志位停止线程
                      t.stop();
                      System.out.println("线程停止了!")
                  }
              }
          }
      }
      
      • 守护线程

        //daemon 守护线程测试
        public class TestDaemon {
            public static void main(String[] args){
                God god = new God();
                You you = new You();
                
                Thread t1 = new Thread(god);
                Thread t2 = new Thread(you);
                
                //设置God为守护者
                t1.setDaemon();
                t1.start();
                
                t2.start();
            }
        }
        
        class God implements Runnable {
            public void run(){
                System.out.println("上帝保佑你")
            }
        }
        
        class You implements Runnable {
            public void run(){
                for(int i = 0; i < 365; i++){
                    System.out.println("你开心的活着");
                }
                System.out.println("======GO OVER!");
            }
        }
        
  4. 同步

  5. 通信问题

  6. 高级主体

  7. 线程优先级

    • 线程的优先调度

    • Thread.MIN_PRIOPITY = 10 1 5

    • getPriority()获取 setPriority(int xxx) 设置优先级

      //优先级测试
      public class TestPriority {
          public static void main(String[] args){
              System.out.println(Thread.currentThread().getName()+"----"+Thread.getPriority());
              
              MyPriority priority = new MyPriority();
              
              //线程
              Thread t1 = new Thread(priority);
              Thread t2 = new Thread(priority);
              Thread t3 = new Thread(priority);
              Thread t4 = new Thread(priority);
              
              t1.start();
              
              t2.setPriority(3);
              t2.start();
              
              t3.setPriority(MAX_PRIORITY);//MAX_PRIORITY = 10;
              t3.start();
              
              t4.setPriority(7);
              t4.start();
          }
      }
      
      class MyPriority implements Runnable {
          public void run(){
              System.out.println(Thread.currentThread().getName()+"----"+Thread.getPriority());
          }
      }
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值