线程和进程解释和创建

一、含义:

进程:是系统进行资源分配和调用的独立单位,每一个进程都有它自己的内存空间和系统资源。
举例:IDEA, 阿里云盘, wegame, steam
线程:是进程中的单个顺序控制流,是一条执行路径
一个进程如果只有一条执行路径,则称为单线程程序。
一个进程如果有多条执行路径,则称为多线程程序。

二、创建线程的两种方式(后面会学到第三种创建方式)

1.继承Thread类,重写里面的Run()方法,将来每个线程里面的逻辑不一样的时候,推荐使用这种方法

class MyThread extends Thread{

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        //run方法是将来线程对象启动时要执行的计算逻辑
        for(int i=1;i<=200;i++){
            System.out.println(getName()+" - "+i);
        }
    }
}

public class ThreadDemo1 {
    public static void main(String[] args) {
        //创建一个线程对象
//        MyThread t1 = new MyThread();
//        MyThread t2 = new MyThread();
        MyThread t1 = new MyThread("李刚");
        MyThread t2 = new MyThread("钱志强");
        //给线程起名字
        // 方式1:调用setName()方法起名字
//        t1.setName("李刚");
//        t2.setName("钱志强");
        // 方式2:使用构造方法起名字

//        t1.run();
//        t2.run();
        t1.start(); // 系统分配资源给线程t1,启动线程,t1线程具备了执行的资格,具体等到抢到cpu执行权的时候才会执行
        t2.start();
    }
}

2.使用实现Runnable接口,并重写里面的方法来创建进程,当将来创建的进程执行逻辑是一样的推荐使用这种方法

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i <= 200; i++) {
            //可以先通过获取当前执行的线程对象,调用内部getName()方法
            System.out.println(Thread.currentThread().getName()+"-"+i);
        }
    }
}

public class RunnableDemo1 {
    public static void main(String[] args) {
        //创建Runnable对象
        MyRunnable r1 = new MyRunnable();
        //创建线程对象
//        Thread t1 = new Thread(r1);
//        Thread t2 = new Thread(r1);
//        Thread t3 = new Thread(r1);
        //创建线程对象同时起名字
        Thread t1 = new Thread(r1, "李刚");
        Thread t2 = new Thread(r1, "祝帅");
        Thread t3 = new Thread(r1, "吴问强");

        //获取线程优先权 默认线程优先级是 5
//        System.out.println("t1: "+t1.getPriority());
//        System.out.println("t2: "+t2.getPriority());
//        System.out.println("t3: "+t3.getPriority());
        t1.setPriority(1); // 1-10
        t1.setPriority(10);
        t1.setPriority(1);

        t1.start();
        t2.start();
        t3.start();
    }
}
posted @ 2024-10-17 21:19  你的镁偷走了我的锌  阅读(20)  评论(0)    收藏  举报