Java学习(九):Java线程的两种实现方式

  线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程序的调度单位。在单个程序中同时运行多个线程完成不同的工作,称为多线程。

  进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。

  Java线程创建的两种方式:

1.继承Thread类

public class MyThread extends Thread
{
    private String name;
    
    public MyThread(String name)
    {
        this.name = name;
    }
    
    public void run()
    {
        try
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.sleep(100); // 增加代码执行时间
                System.out.println("Thread " + this.name + ":" + i);
            }
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args)
    {
        Thread thread1 = new MyThread("one");
        Thread thread2 = new MyThread("two");
        thread1.start();
        thread2.start();
    }
}

输出结果:

Thread one:0
Thread two:0
Thread two:1
Thread one:1
Thread one:2
Thread two:2
Thread one:3
Thread two:3
Thread one:4
Thread two:4

2.实现接口Runnable

 1 public class MyThread2 implements Runnable
 2 {
 3     private String name;
 4     
 5     public MyThread2(String name)
 6     {
 7         this.name = name;
 8     }
 9     
10     public void run()
11     {
12         try
13         {
14             for (int i = 0; i < 5; i++)
15             {
16                 Thread.sleep(100); // 增加代码执行时间
17                 System.out.println("Thread " + this.name + ":" + i);
18             }
19         }
20         catch (InterruptedException e)
21         {
22             e.printStackTrace();
23         }
24     }
25     
26     public static void main(String[] args)
27     {
28         Thread thread1 = new Thread(new MyThread2("one"));
29         Thread thread2 = new Thread(new MyThread2("two"));
30         thread1.start();
31         thread2.start();
32     }
33 }

输出结果同上。

原文地址:https://www.cnblogs.com/moleme/p/4391914.html