generated from SkyrocketStan/LEARN-JAVA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreads1.java
60 lines (52 loc) · 1.56 KB
/
Threads1.java
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
/** @author Stanislav Rakitov */
public class Threads1 {
public static void main(String[] args) {
System.out.println("Main runs");
System.out.println("Thread name: " + Thread.currentThread().getName());
MyRunnable myRunnable = new MyRunnable();
Thread myRunThread = new Thread(myRunnable, "MyRunnableThread");
myRunThread.setPriority(Thread.MAX_PRIORITY);
myRunThread.start();
// My Thread with name and priority
MyThread myThread = new MyThread();
myThread.setName("My Thread");
myThread.setPriority(Thread.MIN_PRIORITY);
myThread.start();
// anonymous threads with normal priority
new MyThread().start();
new MyThread().start();
}
static void printThreadName() {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread runs");
for (int i = 0; i < 10; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName() + ". i " + i);
try {
double random = Math.random() * 100;
Thread.sleep((long) Math.abs(random));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable runs");
Threads1.printThreadName();
for (int i = 0; i <10; i++) {
try {
Thread.sleep(10);
System.out.println("Tik " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}