Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
63 lines (40 loc) · 1.78 KB

File metadata and controls

63 lines (40 loc) · 1.78 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// Java defines two ways to create a runnable object:
// A class can implement the Runnable interface or extend the Thread class.
class MyThread202310 implements Runnable{
String thread_name;
MyThread202310(String thread_name) {
this.thread_name = thread_name;
}
// Inside run(), you can write some code that constitutes a thread. main() is a thread, too.
public void run() {
System.out.println(thread_name + " starting.");
// Because Thread.sleep() can throw an InterruptedException, it must be wrapped in a try block.
try {
// a loop is established that counts from 0 to 9.
for (int count = 0; count < 10; count++) {
Thread.sleep(400); // causes the thread to suspend for 400 milliseconds.
System.out.println("In " + thread_name + ", count is " + count);
}
} catch (InterruptedException e) {
System.out.println(thread_name + " interrupted.");
}
// Thread will end when run() ends.
System.out.println(thread_name + " terminating.");
}
}
public class Creating_a_Thread_annotated {
// From the main thread, you can create other threads.
public static void main(String[] args) {
System.out.println("Main thread starting.");
// Create a runnable object. MyThread202310's object is runnable because it has run() method.
MyThread202310 myThread202310 = new MyThread202310("Child #1");
// You create a thread by instantiating an object of type Thread whose constructor encapsulates an object
// that is runnable.
Thread newThread = new Thread(myThread202310);
// Now, the other thread is constructed.
// Once created, the new thread will not start running until you call its start() method.
newThread.start();
// In essence, start() executes a call to run().
System.out.println("Main thread ending.");
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.