多线程

一、 Process 与 Thread

  1. 进程是执行程序的一次执行过程,是系统资源分配的单位。

  2. 一个进程可以包含若干个线程,至少有一个线程。

 

二、 三种创建方式

  1. Thread class 继承Thread类

    ①自定义线程类继承Thread类

    ②重写run()方法,编写线程执行体

    ③创建线程对象,调用start()方法启动线程

    注意:线程开启不一定立即执行,由CPU调度

 1 // 创建线程方式一:继承Thread类,重写run()方法,调用start()开始线程
 2 public class TestThread1 extends Thread{
 3     @Override
 4     public void run() {
 5         // run方法线程体
 6         for (int i = 0; i < 20; i++) {
 7             System.out.println("我在看代码----"+i);
 8         }
 9     }
10 
11     public static void main(String[] args) {
12         // main线程
13         TestThread1 testThread1 = new TestThread1();//创建线程对象
14         testThread1.start(); //调用start()方法,开启线程
15 
16         for (int i = 0; i < 20; i++) {
17             System.out.println("我在学习多线程----"+i);
18         }
19     }
20 }

  2. Runnable 接口  实现Runnable接口

    ①定义MyRunnable类实现Runnable接口

    ②实现run()方法,编写线程执行体

    ③创建线程对象,调用start()方法启动线程

 1 // 创建线程方式二:实现Runnable接口,重写run方法,执行线程需要丢入Runnable接口实现类,调用start()方法
 2 public class TestThread2 implements Runnable{
 3     @Override
 4     public void run() {
 5         // run方法线程体
 6         for (int i = 0; i < 200; i++) {
 7             System.out.println("我在看代码----"+i);
 8         }
 9     }
10 
11     public static void main(String[] args) {
12         // 创建runnable接口的实现类对象
13         TestThread2 testThread2 = new TestThread2();
14         // 创建线程对象,通过线程对象来开启线程,代理
15         Thread thread = new Thread(testThread2);
16         thread.start();
17         // new Thread(testThread2).start();
18         for (int i = 0; i < 1000; i++) {
19             System.out.println("我在学习多线程---"+i);
20         }
21     }
22 }

  3. Callable接口 实现Callable接口

posted on 2023-02-18 19:43  魔都喷火龙  阅读(21)  评论(0)    收藏  举报

导航