0%

java | 多线程基础

简单的介绍 java 的多线程。

Thread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class T extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {

System.out.println(1);
}
}

public static void main(String[] args) {
T t = new T();
t.start();

for (int i = 0; i < 1000; i++) {
System.out.println(2);
}
}
}

new 一个 Thread 类或者子类对象时,非静态属性(实例属性)都会在内存中重新加载,起不到共用资源的效果,因此我们需要将共用的对象或者变量用static修饰,使其成为类属性,在内存中只加载一次。

Runnable 接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class T implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {

System.out.println(1);
}
}

public static void main(String[] args) {
T t = new T();
new Thread(new T()).start();

for (int i = 0; i < 1000; i++) {
System.out.println(2);
}
}
}

通过实现Runnable接口,通过同一个Runnable接口实现类对象创建多个线程,则多个线程共享Runnable对象。

类似下面的代码

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
34
package com.example.blog;

import lombok.SneakyThrows;

public class T implements Runnable {

public int number = 10;

@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (number < 0) {
return;
}
try {
Thread.sleep(200);
} catch (Exception e) {
;
}
System.out.println(Thread.currentThread() + String.valueOf(number--));
}
}

public static void main(String[] args) {
T t = new T();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
// 下面这个不行
// new Thread(new T()).start();
// new Thread(new T()).start();
// new Thread(new T()).start();
}
}

但是,上面的代码运行的时候,会出现资源重复利用的现象。所以要加锁。

callable

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
34
35
36
37
38
39
40
41
package com.example.blog;

import lombok.SneakyThrows;

import java.util.concurrent.*;

public class T implements Callable<Boolean> {

public int number = 10;

@Override
public Boolean call() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread() + String.valueOf(number--));
}
return true;
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
T t1 = new T();
T t2 = new T();
T t3 = new T();

// 线程池
ExecutorService ser = Executors.newFixedThreadPool(3);

// 提交任务
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);

// 获取结果

Boolean b1 = r1.get();
Boolean b2 = r2.get();
Boolean b3 = r3.get();

// 关闭池子
ser.shutdown();
}
}
请我喝杯咖啡吧~