黑马程序员——第二篇_多线程

来源:互联网 发布:linux df命令显示详解 编辑:程序博客网 时间:2024/05/21 10:12

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

     线程,有时被称为轻量级进程,是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针,寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。由于线程之间的相互制约,致使线程在运行中呈现出间断性。线程也有就绪、阻塞和运行三种基本状态。就绪状态是指线程具备运行的所有条件,逻辑上可以运行,在等待处理机;运行状态是指线程占有处理机正在运行;阻塞状态是指线程在等待一个事件(如某个信号量),逻辑上不可执行。每一个程序都至少有一个线程,若程序只有一个线程,那就是程序本身。

    java中实现多线程有两种方式,分别是继承Thread类和实现Runnable接口,但两者都要实现run()方法。

对于继承Thread类来说,代码大致的框架是

1
2
3
4
5
6
7
8
9
10
11
12
class 类名 extends Thread{
方法1;
方法2
public void run(){
// other code…
}
属性1
属性2
 
}

 举个例子

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
/**
 * @author Rollen-Holt 继承Thread类,直接调用run方法
 * */
class hello extends Thread {
 
    public hello() {
 
    }
 
    public hello(String name) {
        this.name = name;
    }
 
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行     " + i);
        }
    }
 
    public static void main(String[] args) {
        hello h1=new hello("A");
        hello h2=new hello("B");
        
        h1.start();
        h2.start();
    }
 
    private String name;
}

【运行结果】:

A运行     0

B运行     0

B运行     1

B运行     2

B运行     3

B运行     4

A运行     1

A运行     2

A运行     3

A运行     4

对于实现Runnable接口

1
2
3
4
5
6
7
8
9
10
11
12
class 类名 implements Runnable{
方法1;
方法2
public void run(){
// other code…
}
属性1
属性2
 
}

举个例子:

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
/**
 * @author Rollen-Holt 实现Runnable接口
 * */
class hello implements Runnable {
 
    public hello() {
 
    }
 
    public hello(String name) {
        this.name = name;
    }
 
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行     " + i);
        }
    }
 
    public static void main(String[] args) {
        hello h1=new hello("线程A");
        Thread demo= new Thread(h1);
        hello h2=new hello("线程B");
        Thread demo1=new Thread(h2);
        demo.start();
        demo1.start();
    }
 
    private String name;
}

【可能的运行结果】:

线程A运行     0

线程B运行     0

线程B运行     1

线程B运行     2

线程B运行     3

线程B运行     4

线程A运行     1

线程A运行     2

线程A运行     3

线程A运行     4


其实Thread也是实现Runnable接口的,Thread的run()方法是调用了Runnable的run()方法。Thread和Runnable的区别:如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。


0 0