且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java多线程编程(一)

更新时间:2022-04-19 08:05:35



一、线程与进程:

  1.线程:程序中单独顺序的控制流

    线程本身依靠程序进行运行

    线程是程序中的顺序控制流,只能使用分配给程序的资源和环境

  2.进程:执行中的程序

    一个进程可以包含一个或多个线程

    一个进程至少要包含一个线程

  3.单线程:

    程序中至少要存在一个主线程,实际上主方法就是一个主线程。

  4.多线程:

    多线程是在一个程序中运行多个任务

    多线程的目的是更好的使用CPU资源

二、线程的实现

  1.在Java中,线程的实现有两种:继承Thread类,实现Runable接口

  2.Thread类:

    Thread类是在java.lang包中定义的,继承Thread类必须重写run()方法

    定义格式:   

1
2
3
        class className extends Thread{
            run(){};
        }

  3.Runable接口

    具体代码操作:

        第一种实现方式:继承Tread类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.yeqc.thread;
 
public class MyThread extends Thread{
     
    private String name;
     
    public MyThread(String name) {
        this.name = name;
    }
     
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name+":"+i);
        }
        super.run();
    }
 
}
 
package com.yeqc.thread;
 
public class ThreadDemo01 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread("A");
        MyThread t2 = new MyThread("B");
//      t1.run();
//      t2.run();
        //线程的启动是通过start()
        t1.start();
        t2.start();
    }
}

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
B:0
A:0
B:1
A:1
B:2
A:2
B:3
B:4
B:5
B:6
A:3
A:4
A:5
B:7
A:6
B:8
A:7
B:9
A:8
A:9

        第二种实现方式:实现Runable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.yeqc.thread;
 
public class MyRunable implements Runnable{
     
    private String name;
    public MyRunable(String name) {
        this.name = name;
    }
 
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name+":"+i);
        }
    }
     
}
 
package com.yeqc.thread;
 
public class ThreadDemo01 {
    public static void main(String[] args) {
        MyRunable r1 = new MyRunable("A");
        MyRunable r2 = new MyRunable("B");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
    }
}

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
B:0
A:0
B:1
A:1
B:2
B:3
A:2
B:4
B:5
A:3
B:6
A:4
B:7
A:5
B:8
A:6
B:9
A:7
A:8
A:9




本文转自yeleven 51CTO博客,原文链接:http://blog.51cto.com/11317783/1769274