• 周四. 3月 28th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

多线程(一)基础

admin

11月 28, 2021

1.什么是多线程

正常我们执行任务时,任务都是从上到下有序执行,而多线程,就是让多个任务同时执行。

2.创建线程方式一——Thread类

2.1Thread类的构造方法和常用方法

2.2如何使用

1.因为无法直接创建Thread对象,所以我们先创建一个类,继承Thread,重写其中的run方法。

1 public class MyThread extends Thread {
2     @Override
3     public void run() {
4         // TODO Auto-generated method stub
5         for (int i = 0; i < 100; i++) {
6             System.out.println(getName()+":"+i);
7         }
8     }
9 }

2.再创建测试类,创建该类对象,执行对象,注意要使用Thread中的start()方法开启,否则就只是调用run()这个方法。

 1 public class demo02 {
 2     public static void main(String[] args) {
 3         //创建线程对象
 4         MyThread my = new MyThread();
 5         //开启线程
 6         my.start();
 7         //描述主线程任务
 8         for (int i = 1; i < 100; i++) {
 9             System.out.println(Thread.currentThread().getName()+":"+i);
10         }
11     }
12 }

Thread类中,包含几个方法,第一个是getName(),用来获取该线程的线程名,还有一个方法,是返回当前正在执行的线程对象的引用的currentThread()方法,后面这个就是用来在主方法中使用。

3.执行结果:

我们看到两个任务在同时进行,且你的CPU越好,这种频繁切换的数量就会更多。

3.创建线程方式二——Runnable接口

3.1Thread类中与Runnable有关的构造方法

 

 3.2Runnable接口的使用方法

1.也是先创建实现Runnable接口的类

1 public class MyRunnable implements Runnable {
2     @Override
3     public void run() {
4         // TODO Auto-generated method stub
5         for (int i = 1; i < 101; i++) {
6             System.out.println(Thread.currentThread().getName()+":"+i);
7         }
8     }
9 }

2.再创建测试类,创建其线程任务对象,创建线程,执行任务。

 1 public class demo01 {
 2     public static void main(String[] args) {
 3         //创建线程任务对象
 4         MyRunnable mr = new MyRunnable();
 5         //创建线程
 6         Thread th = new Thread(mr);
 7         th.start();
 8         for (int i = 1; i < 101; i++) {
 9             System.out.println(Thread.currentThread().getName()+":"+i);
10         }
11     }
12 }

3.执行结果

也是两个线程同时执行,那区别在什么地方?

区别在于,直接继承Thread类时,因为规定一个类只能继承一个类,所以直接断掉了继承其他类的办法,而使用实现Runnable接口的方法,因一个类可以实现多个接口,所以不影响类其本身的其他操作。

4.匿名内部类

我们在如果只重写一个方法,就可以使用匿名内部类的办法。

 1 public static void main(String[] args) {
 2         //1.继承Thread类
 3         //创建Thread类的子类对象
 4         Thread t = new Thread(){
 5             public void run() {
 6                 for (int i = 1; i < 101; i++) {
 7                     System.out.println(getName()+":"+i);
 8                 }
 9             }
10         };
11         //开启线程
12         t.start();
13         //2.实现Runnable接口
14         //创建线程任务对象
15         Runnable r = new Runnable(){
16             public void run() {
17                 for (int i = 1; i < 101; i++) {
18                     System.out.println(Thread.currentThread().getName()+":"+i);
19                 }
20             }
21         };
22         //创建线程对象
23         Thread t1 = new Thread(r);
24         t1.start();
25     }

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注