为什么Java Thread会将打印扭曲到控制台

时间:2014-03-16 18:47:53

标签: java multithreading

我在Java中有一个多线程应用程序。在其中一个线程的run方法中,我有一个

System.out.println("Print something something something")
语句。我遇到的问题是,有时候,我从此打印件获得的输出不是"Print something something something"而是"something Print something something"以及其他一些变体。请问这是什么原因?我在run方法中调用的方法如下所示。

public synchronized void generateRequests() {

        String name;
        int qty;
        int index = 0;
        System.out.print("Customer " + custId + " requests, ");
        for (Item i : items) {
            name = i.getName();
            qty = randNoGenerator(0, 10);
            items.set(index, new Item(name, qty));
            index++;
            System.out.print(qty + " " + name + ", ");
        }

        s.serviceRequests(this);
    }

1 个答案:

答案 0 :(得分:1)

了解此问题的示例代码。

代码:

public class MultiThreading implements Runnable {

    private String id;
    private double qt;

    public MultiThreading(String id, double qt) {
        this.id = id;
        this.qt = qt;
    }

    public static void main(String[] args) {
        MultiThreading obj = new MultiThreading("1", 1000);
        for (int i = 0; i < 5; i++) {
            // Thread thread = new Thread(new MultiThreading(String.valueOf(i), (i * 1000)));
            Thread thread = new Thread(obj);
            thread.setPriority(i + 1);
            thread.start();
        }
    }

    public synchronized void generateRequests() {

        System.out.println("Customer:" + this.id);
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Quentity:" + this.qt);
    }

    @Override
    public void run() {
        generateRequests();
    }

}
  • 在同一个对象上调用synchronized方法(这不会混淆输出)

        MultiThreading obj = new MultiThreading("1", 1000);
        for (int i = 0; i < 5; i++) {                
            Thread thread = new Thread(obj);
            thread.setPriority(i + 1);
            thread.start();
        }
    

输出:

Customer:1
Quentity:1000.0
Customer:1
Quentity:1000.0
Customer:1
Quentity:1000.0
Customer:1
Quentity:1000.0
Customer:1
Quentity:1000.0
  • 在不同的对象上调用synchronized方法(这会混淆输出,下次运行时可能会有所不同)

       for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new MultiThreading(String.valueOf(i), (i * 1000)));
            thread.setPriority(i + 1);
            thread.start();
        }
    

输出:

Customer:0
Customer:1
Customer:4
Customer:2
Customer:3
Quentity:0.0
Quentity:2000.0
Quentity:3000.0
Quentity:1000.0
Quentity:4000.0