Java:线程顺序

标签 java multithreading

下面代码发现输出结果不是顺序的,不是从小到大的顺序,如何保证是从小到大的顺序?

java代码

public class TestSync {  

    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        for (int i = 0; i < 10; i++) {  
            new Thread(new Thread1()).start();  
        }  

    }  

    public int getNum(int i) {  
        synchronized (this) {  
            i++;  
        }  
        return i;  
    }  

    static class Thread1 implements Runnable {  
        static Integer value = 0;  
        @Override  
        public void run() {  
            TestSync ts = new TestSync();  
            value = ts.getNum(value);  
            System.out.println("thread1:" + value);  
        }  
    }  

}  

最佳答案

你想完成什么?您的代码仅同步对特定 TestSync 实例的调用。由于每个线程都创建自己的实例,所以就像您根本没有同步任何东西一样。您的代码没有做任何事情来同步或协调不同线程之间的访问。

我建议以下代码可能更符合您要完成的目标:

public static void main (String[] args) throws java.lang.Exception {
        for (int i = 0; i < 10; i++) {  
            new Thread1().start();  
        }  
}

//no need for this to be an instance method, or internally synchronized
public static int getNum(int i) {  
       return i + 1;  
}

static class Thread1 extends Thread {  
    static Integer value = 0;  

    @Override  
    public void run() {  
        while (value < 100) {
            synchronized(Thread1.class) {  //this ensures that all the threads use the same lock
                value = getNum(value);  
                System.out.println("Thread-" + this.getId() + ":  " + value);  
            }

            //for the sake of illustration, we sleep to ensure some other thread goes next
            try {Thread.sleep(100);} catch (Exception ignored) {} 
        }
    }  
}

此处为实例:http://ideone.com/BGUYY

请注意,getNum() 本质上是多余的。如果将 value = getNum(value); 替换为简单的 value++;,上面的示例将同样有效。

关于Java:线程顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12152493/

相关文章:

java - 如何更快地加密文件

Java泛型方法通过使用类型开关获取类型值

python - 检测线程何时在 python 应用程序中运行?

Java 客户端-服务器聊天应用程序获取 java.net.SocketException : Socket closed

java - 二维数组重写

java - 使用任意键将 JSON 反序列化为 Map

c# - ThreadPool RegisterWaitForSingleObject 的资源使用

c# - C++ 新手,想在 MFC 应用程序中创建后台线程

c - pthread_mutex_timedlock() 过早退出而不等待超时

java - 使用 java 的正则表达式查找子字符串