多线程基础信息及实例

最近在学习多线程基础,所以写篇文章记录一下,若有不恰当的地方,还请各位大佬多多指教

一.进程和线程的区别

  • 线程 : 线程是一组指令的集合,或者是程序的特殊段,它可以在程序里独立执行。也可以把它理解为代码运行的上下文。说白了就是进程的一条执行路径
  • 进程:每个正在系统上运行的程序都是一个进程。

总结:进程是所有线程的集合,线程是进程的一部分,每一个线程是进程中的一条执行路径。

二.多线程

  • 定义:同一时刻有多条不同的执行路径 同时进行执行
  • 作用:为了提高程序的效率

三. 同步异步概念

     同步特征(单线程):代码从上往下进行执行
     异步特征(采用多线程):方法之间都有自己独立线程进行执行 互不影响 开新的一条执行路径,不会影响其他线程

如图在这里插入图片描述

四.多线程创建方式

1.继承Thread类
  1. 继承Thread类 重写run方法
// 1.继承Thread类 重写run方法 run方法中 需要线程执行代码
class ThreadDemo01 extends Thread {
    // run方法中 需要线程执行代码
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("子。。i:" + i);
        }
    }
}
  1. main方法
public static void main(String[] args) {
       System.out.println("main...主线程开始。。");
       // 1.创建线程
       ThreadDemo01 threadDemo01 = new ThreadDemo01();
       // 2.启动线程
       threadDemo01.start();
       //threadDemo01.run();
       for (int i = 0; i < 10; i++) {
           System.out.println("main。。i:" + i);
       }
       System.out.println("main...主线程结束...");
   }
  1. 运行结果
    在这里插入图片描述
2.实现Runnable接口
  1. 实现Runnable接口 重写run方法
class ThreadDemo2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0;i<10;i++){
            System.out.println("子i:"+i);
        }
    }
}
  1. main方法
 public static void main(String[] args) {
        System.out.println("main...主线程开始。。");
        // 创建线程
        ThreadDemo2 threadDemo2 = new ThreadDemo2();
        Thread thread = new Thread(threadDemo2);
        // 启动线程
        thread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("main。。i:" + i);
        }
        System.out.println("main...主线程结束...");
    }
3.使用匿名内部类方式
   public static void main(String[] args) {
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                for (int i = 0;i<10;i++){
                    System.out.println("子i:"+i);
                }
            }
        });
        thread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("main。。i:" + i);
        }
        System.out.println("main...主线程结束...");
    }
4.使用线程池(待学习)

注意:开启线程不是run方法 而是start方法

五.获取线程对象及名称

  • 常用线程api方法
    • start() 启动线程
    • currentThread() 获取当前线程对象
    • getID() 获取当前线程ID Thread-编号 该编号从0开始
    • getName() 获取当前线程名称
    • sleep(long mill) 休眠线程
    • Stop() 停止线程,
  • 常用线程构造函数
    • Thread() 分配一个新的 Thread 对象
    • Thread(String name) 分配一个新的 Thread对象,具有指定的 name正如其名。
    • Thread(Runable r) 分配一个新的 Thread对象
    • Thread(Runable r, String name) 分配一个新的 Thread对象

六.守护线程

  • 定义

    • 用户线程:是指用户自定义创建的线程,主线程停止,用户线程不会停止
    • 守护线程:当进程不存在或主线程停止,守护线程也会被停止。
      使用setDaemon(true)方法设置为守护线程
  • 示例

    public static void main(String[] args) {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(100);
					} catch (Exception e) {
						// TODO: handle exception
					}
					System.out.println("我是子线程...");
				}
			}
		});
		thread.setDaemon(true);
		thread.start();
		for (int i = 0; i < 10; i++) {
			try {
				Thread.sleep(100);
			} catch (Exception e) {

			}
			System.out.println("我是主线程");
		}
		System.out.println("主线程执行完毕!");
	}

七.多线程运行状态

在这里插入图片描述

八.join()方法

  • 作用:当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1
public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            // 子线程
            public void run() {
                for (int i = 0; i < 30; i++) {
                    System.out.println("子1。。i:" + i);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 主线程
        for (int i = 0; i < 10; i++) {
            System.out.println("main。。i:" + i);
        }
    }

九.优先级

  • priority来控制优先级,范围为1-10,其中10最高,默认值为5
class PrioritytThread implements Runnable {

	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().toString() + "---i:" + i);
		}
	}
}
public static void main(String[] args) {
		PrioritytThread prioritytThread = new PrioritytThread();
		Thread t1 = new Thread(prioritytThread);
		Thread t2 = new Thread(prioritytThread);
		t1.start();
		// 注意设置了优先级, 不代表每次都一定会被执行。 只是CPU调度会有限分配
		t1.setPriority(10);
		t2.start();
		
	}

十. 题目

  • 现 在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行
public static void main(String[] args) {
       final Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 20; i++) {
                    System.out.println("t1,i:" + i);
                }
            }
        });
        final Thread t2 = new Thread(new Runnable() {
            public void run() {
                try {
                    t1.join();
                } catch (Exception e) {
                    // TODO: handle exception
                }
                for (int i = 0; i < 20; i++) {
                    System.out.println("t2,i:" + i);
                }
            }
        });
        final Thread t3 = new Thread(new Runnable() {
            public void run() {
                try {
                    t2.join();
                } catch (Exception e) {
                    // TODO: handle exception
                }
                for (int i = 0; i < 20; i++) {
                    System.out.println("t3,i:" + i);
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }

最近在学习多线程基础,所以写篇文章记录一下,若有不恰当的地方,还请各位大佬多多指教

发布了13 篇原创文章 · 获赞 3 · 访问量 638

猜你喜欢

转载自blog.csdn.net/weixin_45183530/article/details/104689176