Java线程的创建

目录

一.线程和进程

1.概念

2,进程和线程的区别

二.线程的五种创建方式

1.继承Thread类

2.实现Runnable接口

3.继承Thread类,使用匿名内部类

4.实现Runnable接口,使用匿名内部类

5.使用Lambda表达式创建线程

扫描二维码关注公众号,回复: 14995934 查看本文章

一.线程和进程

1.概念

     线程:一个线程就是一个 "执行流". 每个线程之间都可以按照顺讯执行自己的代码. 多个线程之间 "同时" 执行着多份代码。通俗点说就是一个应用程序中执行着不同的功能,比如我们用微信聊天,微信运行起来相当于一个进程,而我们使用微信聊天,发朋友圈等等就相当于不同的线程。

     进程:是正在运行的程序的实例,是一个具有一定独立功能的程序关于某个数据集合的一次运行活动,通俗点说相当于一个跑起来的程序。

2,进程和线程的区别

  • 1.一个进程至少包含一个或者多个线程;
  • 2.进程有自己独立的内存空间和文件和描述符表,同一个进程中的多个线程,公用一个地址和文件描述符表;
  • 3.进程是操作系统资源分配的基本单位,线程是操作系统调度执行的基本单位
  • 4.进程之间具有独立性,一个进程崩了,不会影响到其他进程;同一个进程中的多个线程,一个线程挂了,可能影响到整个进程或者其他线程;

二.线程的五种创建方式

1.继承Thread类

class Mythread extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("线程1");
            try {
                Thread.sleep(1000);//控制打印的速度
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        //创建一个线程
        Thread thread = new Mythread();

        //启动线程
        thread.start();
        while (true) {
            System.out.println("主线程");
            Thread.sleep(1000);
        }

    }
}

结果:

 我们可以看到这里2个线程交替打印,但是此处的交替不是按照一定规律的交替,2个线程同事进行,我们也无法区别哪一个先打印哪一个!


2.实现Runnable接口

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程1");
    }
}

public class Demo2 {
    public static void main(String[] args) {
        //创建线程
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        //启动线程
        thread.start();
        System.out.println("主线程");

    }
}

3.继承Thread类,使用匿名内部类

public class Demo3 {
    public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run() {
                System.out.println("线程1");
            }
        };
        thread.start();

        System.out.println("主线程");

    }
}

4.实现Runnable接口,使用匿名内部类

public class Demo4 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1");
            }
        }) {

        };
        thread.start();
        System.out.println("主线程");

    }
}

5.使用Lambda表达式创建线程

public class Demo5 {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("线程1");
        });
        thread.start();
        System.out.println("主线程");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_63635730/article/details/129462213