创建线程

常用创建线程方式

方式一:继承Thread类

1
2
3
4
5
6
public class SimpleThread extends Thread {
@Override
public void run() {
System.out.println("运行中--->>>");
}
}

方式二:实现Runnable接口

1
2
3
4
5
public class SimpleRunnable implements Runnable {
public void run() {
System.out.println("运行中--->>>");
}
}

Thread和Runnable的不同点

  1. Thread 是类,而Runnable是接口;
    Thread本身是实现了Runnable接口的类。我们知道“一个类只能有一个父类,但是却能实现多个接口”,因此Runnable具有更好的扩展性。

  2. Runnable还可以用于“资源的共享”。
    多个线程都是基于某一个Runnable对象建立的,它们会共享Runnable对象上的资源。

Thread多线程例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class SimpleThread extends Thread {
private int ticket = 10;
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (this.ticket > 0) {
System.out.println(this.getName() + " 卖票:ticket" + this.ticket--);
}
}
}
}
public class App {
public static void main(String[] args) {
SimpleThread st1 = new SimpleThread();
SimpleThread st2 = new SimpleThread();
SimpleThread st3 = new SimpleThread();
st1.start();
st2.start();
st3.start();
}
}

输出结果:

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
Thread-2 卖票:ticket10
Thread-1 卖票:ticket10
Thread-0 卖票:ticket10
Thread-0 卖票:ticket9
Thread-1 卖票:ticket9
Thread-2 卖票:ticket9
Thread-1 卖票:ticket8
Thread-0 卖票:ticket8
Thread-1 卖票:ticket7
Thread-2 卖票:ticket8
Thread-1 卖票:ticket6
Thread-0 卖票:ticket7
Thread-1 卖票:ticket5
Thread-2 卖票:ticket7
Thread-1 卖票:ticket4
Thread-0 卖票:ticket6
Thread-1 卖票:ticket3
Thread-2 卖票:ticket6
Thread-1 卖票:ticket2
Thread-0 卖票:ticket5
Thread-1 卖票:ticket1
Thread-2 卖票:ticket5
Thread-0 卖票:ticket4
Thread-2 卖票:ticket4
Thread-0 卖票:ticket3
Thread-2 卖票:ticket3
Thread-0 卖票:ticket2
Thread-2 卖票:ticket2
Thread-0 卖票:ticket1
Thread-2 卖票:ticket1

结果表明:

  1. 每个SimpleThread线程都会卖出10张票
  2. 主线程main创建并启动3个SimpleThread子线程。每个子线程都各自卖出了10张票。

Runnable多线程例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class SimpleRunnable implements Runnable {
private int ticket = 10;
public void run() {
for (int i = 0; i < 20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName() + " 卖票:ticket" + this.ticket--);
}
}
}
}

public class App {
public static void main(String[] args) {
SimpleRunnable sr = new SimpleRunnable();
// 启动3个线程t1,t2,t3(它们共用一个Runnable对象),这3个线程一共卖10张票!
Thread t1 = new Thread(sr);
Thread t2 = new Thread(sr);
Thread t3 = new Thread(sr);
t1.start();
t2.start();
t3.start();
}
}

输出结果:

1
2
3
4
5
6
7
8
9
10
Thread-0 卖票:ticket10
Thread-1 卖票:ticket8
Thread-2 卖票:ticket9
Thread-1 卖票:ticket6
Thread-0 卖票:ticket7
Thread-1 卖票:ticket4
Thread-2 卖票:ticket5
Thread-1 卖票:ticket2
Thread-0 卖票:ticket3
Thread-2 卖票:ticket1

结果表明:

  1. SimpleThread线程也是卖10张票,不同的是它实现了Runnable接口,而不是继承Thread类
  2. 主线程main创建并启动3个子线程,而且这3个子线程都是基于“sr这个Runnable对象”而创建的。运行结果是这3个子线程一共卖出了10张票。这说明它们是共享了SimpleThread接口的。

其他创建方式

//todo