Moh*_*hit 3 java multithreading
我尝试了以下代码:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static int i = 0;
public static void main(String[] args) {
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
new Thread(t4).start();
new Thread(t5).start();
new Thread(t6).start();
}
private static void countMe(String name){
i++;
System.out.println("Current Counter is: " + i + ", updated by: " + name);
}
private static Runnable t1 = new Runnable() {
public void run() {
try{
for(int i=0; i<2; i++){
countMe("t1");
}
} catch (Exception e){}
}
};
private static Runnable t2 = new Runnable() {
public void run() {
try{
for(int i=0; i<2; i++){
countMe("t2");
}
} catch (Exception e){}
}
};
private static Runnable t3 = new Runnable() {
public void run() {
try{
for(int i=0; i<2; i++){
countMe("t3");
}
} catch (Exception e){}
}
};
private static Runnable t4 = new Runnable() {
public void run() {
try{
for(int i=0; i<2; i++){
countMe("t4");
}
} catch (Exception e){}
}
};
private static Runnable t5 = new Runnable() {
public void run() {
try{
for(int i=0; i<2; i++){
countMe("t5");
}
} catch (Exception e){}
}
};
private static Runnable t6 = new Runnable() {
public void run() {
try{
for(int i=0; i<2; i++){
countMe("t6");
}
} catch (Exception e){}
}
};
}
Run Code Online (Sandbox Code Playgroud)
并且在ideone上得到了输出:
Current Counter is: 1, updated by: t1
Current Counter is: 2, updated by: t1
Current Counter is: 3, updated by: t2
Current Counter is: 4, updated by: t2
Current Counter is: 5, updated by: t3
Current Counter is: 6, updated by: t3
Current Counter is: 7, updated by: t4
Current Counter is: 8, updated by: t4
Current Counter is: 9, updated by: t5
Current Counter is: 10, updated by: t5
Current Counter is: 11, updated by: t6
Current Counter is: 12, updated by: t6
似乎一切都以线性方式进行,即按照我创建它们的顺序逐个称为函数countMe的线程.多线程意味着它们可能会出现故障.我在这里失踪了什么?我运行的机器(我在ideone.com上试过)的配置是这样的吗,它运行线程按顺序创建?
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |