Ach*_*ver 9 java multithreading
据我所知,sleep()它用于在指定时间内休眠一个线程.我制成的纤维束的例子-比如1我正在作为输出1,2,3,4因为我只创建一个.在例2中,我创建的线程的2个实例,我获得输出1,1,2,2,3,3,4,4.
为什么输出不1,2,3,4第一个线程,然后1,2,3,4为第二个?
例1:
// Using sleep() method
public class Aaa extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);
} catch(InterruptedException e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args){
Aaa m1=new Aaa();
m1.start();
}
}
Output:
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
例2:
// Using sleep() method
public class Aaa extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500); // sleeps thread
} catch(InterruptedException e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args){
Aaa m1=new Aaa(); // creating one object
Aaa m2=new Aaa(); // creating second object of a class
m1.start(); // calls run method
m2.start();
}
}
Output:
1
1
2
2
3
3
4
4
Run Code Online (Sandbox Code Playgroud)
您已创建了两个Runnable对象.如果你通过调用他们的run方法运行它们,你会得到你想象的:
Aaa m1=new Aaa(); // creating one object
Aaa m2=new Aaa(); // creating second object of a class
System.out.println("Calling m1.run()");
m1.run(); // we call run method
System.out.println("Calling m2.run()");
m2.run();
Run Code Online (Sandbox Code Playgroud)
产量
Calling m1.run()
1
2
3
4
Calling m2.run()
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
因为该方法执行两次,一个接一个.
需要注意的是调用run的方法Runnable/Thread是不运行一个线程的正常方式.您通常会使用该start方法.
但是,如果你把每个人放在一个Thread和start它们中:
Aaa m1=new Aaa(); // creating one object
Aaa m2=new Aaa(); // creating second object of a class
System.out.println("Calling m1.start()");
m1.start(); // thread calls run method
System.out.println("Calling m2.start()");
m2.start();
Run Code Online (Sandbox Code Playgroud)
现在,每个对象并行运行在自己的线程中,因此输出是交错的:
Calling m1.start()
Calling m2.start()
1 < From thread 1
1 < From thread 2
2 ...
2
3
3
4
4
Run Code Online (Sandbox Code Playgroud)
顺序显然可以根据线程如何交错而变化.
可能令你困惑的一件事是你选择了extend Thread.这是不鼓励的.最好implement Runnable- 像这样:
public class Aaa implements Runnable {
public void run() {
for (int i = 1; i < 5; i++) {
try {
Thread.sleep(500); // sleeps thread
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args) {
Aaa m1 = new Aaa(); // creating one object
Thread t1 = new Thread(m1); // Its thread
Aaa m2 = new Aaa(); // creating second object of a class
Thread t2 = new Thread(m2); // Its thread
t1.start(); // calls m's run method in a new thread.
t2.start();
}
}
Run Code Online (Sandbox Code Playgroud)
现在更清楚的是,您的对象在两个不同的线程中运行,因此并行运行.
| 归档时间: |
|
| 查看次数: |
7408 次 |
| 最近记录: |