Java:线程顺序 [英] Java: Thread sequential order

查看:60
本文介绍了Java:线程顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Following code found that output results is not the order, not from small to large, how to guarantee it is order from small to large?

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实例的调用.由于每个线程都创建自己的实例,因此就像您根本不同步任何内容一样.您的代码没有做任何事情来同步或协调不同线程之间的访问.

What are you trying to accomplish? Your code is only synchronizing calls made to a particular TestSync instance. Since each thread creates its own instance, it's like you are not synchronizing anything at all. Your code is not doing anything to synchronize or coordinate accesses across the different threads.

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

I'd suggest the following code may be more along the lines of what you are trying to accomplish:

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++;,则上面的示例将发挥相同的作用.

Note that getNum() is essentially superfluous. The example above would work the same if you replaced value = getNum(value); with a simple value++;.

这篇关于Java:线程顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆