• 多线程


    1.进程概念:进程指正在运行的程序。确切的来说,当一个程序进入内存运行,

    即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能。

    2.线程概念:是进程中的一个执行单元,负责当前进程中程序的执行,一个进程中至少有一个线程。

    一个进程中是可以有多个线程的,这个应用程序也可以称之为多线程程序。

    3.Thread(线程)类

    创建线程的方式

    a.继承Thread类原型

    public static void main(String[] args) {
            
            System.out.println(Thread.currentThread().getName());//获得当前线程名称    
            MyThread mt = new MyThread("张三");//创建线程并指定线程名称
            mt.setName("李四");//修改线程名称
            //开启线程
            mt.start();
            for(int i = 0 ;i<=100;i++){        
                System.out.println("main..."+i);
            }    
        }

    建一个Thread的子类 重写run方法

     1 public class MyThread extends Thread {
     2         
     3     public MyThread(String name) {
     4         //调用父级的构造方法对线程名进行赋值
     5         super(name);
     6     }
     7 
     8     //重写 run方法
     9     public void run() {
    10         System.out.println("线程名字"+getName());
    11         for(int i =0;i<100;i++){        
    12             System.out.println("run..."+i);        
    13         }
    14     }        
    15 }

    注意:开启线程用start()方法 不是run();

    Thread.sleep()在指定毫秒数内让当前执行的线程休眠

    b.实现Runnable接口

    public static void main(String[] args) {    
            //创建线程任务对象
            MyRunnable mr = new MyRunnable();
            //创建线程处对象传入任务对象
            Thread th = new Thread(mr);
            // 开启线程
            th.start();
            
            for (int i = 0; i < 100; i++) {
                System.out.println("main..." + i);
            }
        }
    public class MyRunnable implements Runnable{
        //线程任务
        public void run() {    
            
            for(int i =0;i<100;i++){        
                System.out.println("run..."+i);        
            }        
        }
        
    }

    b方式更好:1解决了单继承局限性   2降低耦合性

    4.线程的匿名内部类使用方法

    new Thread() {
                public void run() {
                    for (int x = 0; x < 40; x++) {
                        System.out.println(Thread.currentThread().getName()
                                + "...X...." + x);
                    }
                }
            }.start();
    Runnable r = new Runnable() {
                public void run() {
                    for (int x = 0; x < 40; x++) {
                        System.out.println(Thread.currentThread().getName()
                                + "...Y...." + x);
                    }
                }
            };
            new Thread(r).start();

    1.1.1 继承Thread类原理

  • 相关阅读:
    nginx 配置详解
    ngnix 负载均衡
    nginx 安装搭建与配置介绍
    11.15java实习生面试总结
    笔试题:编写一个用户注册接口
    java第一次笔试+面试总结
    《啊哈算法》读后总结(下)
    java常见排序算法
    Tomcat安装及配置教程
    算法题:购买n个苹果,苹果6个一袋或者8个一袋,若想袋数最少,如何购买?
  • 原文地址:https://www.cnblogs.com/lxzwhite/p/10553051.html
Copyright © 2020-2023  润新知