📄 twothreadsdemo.java
字号:
class SimpleThread extends Thread {
/*
The first method in the SimpleThread class is
a constructor that takes a String as its only argument.
This constructor is implemented by calling a superclass constructor
that sets the Thread's name, which is used later in the program
*/
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
public class TwoThreadsDemo {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
/*The next method in the SimpleThread class is the
run method. This method, the heart of any Thread,
defines what the Thread does when it's running.
The run method of the SimpleThread class overrides the empty
method implementation in the Thread class and contains
a for loop that iterates ten times. In each iteration,
the method displays the iteration number and the name of
the Thread. Then the method sleeps for a random interval
of up to 1 second. After the loop has finished, the run method
prints DONE! and the name of the thread. That's it for the SimpleThread class.
Let's put it to use in TwoThreadsDemo.
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -