0

我在 Java 线程中观察到一种奇怪的行为,它们似乎以顺序方式运行。以下是代码片段

class ThreadUnsafeClass {

    private static int y;

    public static void incrementY() {
        y++;
    }

    public static int getY() {
        return y;
    }

}

public class MultiThreadedClass implements Runnable {
    int threadId;

    MultiThreadedClass (int threadId) {
        this.threadId = threadId;
    }

    @Override
    public void run() {

        System.out.println("Number:"+ threadId + ";Thread Unsafe Old Value:" + ThreadUnsafeClass.getY());

        try {
            if (threadId == 1 || threadId ==2) {
                Thread.sleep(60000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace(); 
        }
        ThreadUnsafeClass.incrementY();

        System.out.println("Number:"+ threadId + ";Thread Unsafe New Value:" + ThreadUnsafeClass.getY());
    }

    public static void main (String []args) {
        MultiThreadedClass thread1 = new MultiThreadedClass(1);
        MultiThreadedClass thread2 = new MultiThreadedClass(2);
        MultiThreadedClass thread3 = new MultiThreadedClass(3);
        MultiThreadedClass thread4 = new MultiThreadedClass(4);
        thread1.run();
        thread2.run();
        thread3.run();
        thread4.run();
   }
}

以下是相同的输出:

Number:1;Thread Unsafe Old Value:0
Number:1;Thread Unsafe New Value:1
Number:2;Thread Unsafe Old Value:1
Number:2;Thread Unsafe New Value:2
Number:3;Thread Unsafe Old Value:2
Number:3;Thread Unsafe New Value:3
Number:4;Thread Unsafe Old Value:3
Number:4;Thread Unsafe New Value:4

从上面的输出可以看出,即使线程 1 和 2 等待了一段合理的时间,即 60 秒,线程 3 和 4 仍然只有在它们完成执行时才执行。为什么线程不并行执行,当一个线程休眠时,为什么另一个线程不继续执行?我在某个地方出错了吗?

4

3 回答 3

6

您需要创建一个Thread引用Runnableand call start(),而不是run()在实际类上。制作某些东西Runnable并不意味着它会自动在单独的线程中运行。

例如

(new Thread(myRunnable)).start()

为什么和之间的Runnable分离Thread?我可以将Runnable其放入线程池中。下一个可用线程将运行该Runnable. (例如参见 Java Executor框架)Runnable仅表示对象可用于线程。

于 2012-11-05T14:36:57.253 回答
3

您应该扩展Thread并调用thread.start()而不是thread.run(),因为thread1.run()同步调用该方法。thread.startrun()异步调用,达到你想要的效果。

您还可以使用此构造函数构造Thread一个Runnable

Thread(Runnable r)

于 2012-11-05T14:38:11.340 回答
2

Runnable让一个类实现在不同的线程中运行是不够的。代替

MultiThreadedClass thread1 = new MultiThreadedClass(1);
MultiThreadedClass thread2 = new MultiThreadedClass(2);
MultiThreadedClass thread3 = new MultiThreadedClass(3);
MultiThreadedClass thread4 = new MultiThreadedClass(4);
thread1.run();
thread2.run();
thread3.run();
thread4.run();

尝试做

new Thread(new MultiThreadedClass(1)).start();
new Thread(new MultiThreadedClass(2)).start();
new Thread(new MultiThreadedClass(3)).start();
new Thread(new MultiThreadedClass(4)).start();
于 2012-11-05T14:38:35.833 回答