Repository navigation
Expand file tree
/
Copy pathThread1.java
More file actions
72 lines (65 loc) · 1.9 KB
/
Copy pathThread1.java
File metadata and controls
72 lines (65 loc) · 1.9 KB
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
72
package thread;
public class Thread1 {
public static void main(String[] args) throws InterruptedException {
example1();
example2();
example3();
}
/**
* Создание потока через класс
*/
public static void example1() {
MyThread myThread = new MyThread();
myThread.start(); // создаёт новый поток и запускает метод run()
MyThread myThread2 = new MyThread();
myThread2.start();
}
/**
* Создание потока через Runnable
*/
public static void example2() {
Thread myThread = new Thread(new Runner());
myThread.start();
}
/**
* Создание потока через Runnable лямбда синтаксис
*/
public static void example3() {
Thread myThread = new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("From example3 thread " + i);
}
});
myThread.start();
}
}
class Runner implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("From example2 thread " + i);
}
}
}
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("From example1 thread " + i);
}
}
}