0%

多线程-入门

Multithreading-入门

多线程-入门

  • 1.线程的生命周期
  • 2.创建线程
  • 3.多线程编程的主要概念
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class Multithreading {

public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}

/**
* 1.线程的生命周期:新建、就绪、阻塞、运行、死亡
* 新建:new
* 就绪:新建状态调用start()方法,手动调用。
* 运行:就绪状态调用run()方法,自动调用。就绪状态的线程获取到满足运行的 CPU 资源,就执行 run(),
* 阻塞:线程执行sleep(睡眠)、suspend(挂起).
* 等待阻塞:运行状态执行wait()
* 同步阻塞:线程获取synchronized同步锁失败。
* 其他阻塞:调用线程的sleep()或join()发出来I/O请求。当sleep() 状态超时,join() 等待线程终止或超时,或者 I/O 处理完毕,线程重新转入就绪状态。
* 死亡:线程执行完或有终止条件
*/

/**
* 2.创建线程
* 1.实现Runnable接口
* 2.继承Thread类
* 3.通过 Callable 和 Future 创建线程
*/

//2.1.实现Runnable接口
class RunnableDemo implements Runnable{

private Thread t;
private String threadName;

RunnableDemo (String name){
this.threadName = name;
System.out.println("Thread " + threadName + "新建 ");
}

// 重写run方法
// 运行
@Override
public void run() {
System.out.println("Thread " + threadName + "运行");

try {
for (int i = 0; i < 4; i++) {
System.out.println("第"+i+"次执行Thread: " + threadName);
// 阻塞
Thread.sleep(50);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + threadName + "死亡");
}

public void start(){
if (t == null) {
// 新建
t = new Thread (this, threadName);
// 就绪
t.start();
System.out.println("Thread " + threadName + " 就绪");
}
}
}


3.多线程编程的主要概念:

  • 线程同步
    
  • 线程间通信
    
  • 线程死锁
    
  • 线程控制:挂起、停止和恢复
    
  • 线程池