如何在java中同时运行两个线程

时间:2015-12-23 11:21:21

标签: java multithreading

我是java新手,我正在尝试学习线程。

我期待替代/* Removing this makes it work */ .breadcrumb__text::after { font-family: "FontAwesome"; font-weight: 400; } /* Don't remove anything below */ .breadcrumb__text--first { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } * { box-sizing: inherit; } html { box-sizing: border-box; } html, body { padding: 0; margin: 0; } body { display: flex; flex-flow: column nowrap; align-items: stretch; } .layout_wrapper { flex: 1 1 auto; display: flex; flex-flow: row nowrap; align-items: stretch; } .layout_container__content { flex: 0 0 75vw; } .layout_container__sidebar { flex: 0 0 25vw; } .content { display: flex; flex-flow: row wrap; justify-content: space-between; align-items: stretch; } .content__header { outline: 1px solid blue; background-color: #434649; color: #ffffff; flex: 0 0 100%; display: flex; flex-flow: row nowrap; } .breadcrumb { outline: 3px dashed purple; flex: 1 1 auto; display: flex; flex-flow: row wrap; justify-content: flex-start; } .breadcrumb__text { flex: 0 0 2em; overflow: hidden; text-indent: 100%; white-space: nowrap; position: relative; text-align: center; } .breadcrumb__text::after { content: '\f105'; padding: 0; text-indent: 0; position: absolute; top: 0; right: 0; width: 100%; } .breadcrumb__text--first { flex: 0 0 0; } .breadcrumb__text--first::after { content: none; } .breadcrumb__link { flex: 0 0 auto; display: inline-block; font-size: 0.8571rem; } .breadcrumb__current { flex: 0 0 100%; margin: 0; } .page_tools { outline: 3px dashed red; flex: 0 0 auto; display: flex; flex-flow: row nowrap; list-style: none outside none; } hello this is thread one的输出。但我得到的输出如下:

hello this is thread two

以下是我的代码。任何人都可以帮助我,为什么我得到这个输出而不是预期。我可以做什么来并行运行两个线程。

hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two

7 个答案:

答案 0 :(得分:3)

仅仅因为线程可以交织并不意味着它们。你的线程运行得太快了。尝试添加Thread.sleep()以使其运行时间更长。

答案 1 :(得分:3)

这里的问题是PrintStream是synchronized,这是不公平的。

    final Lock lock = new ReentrantLock(true); //create fair lock
                        //after running this code change it to
                        //ReentrantLock(false); to see what happens

    // This is the first block of code
    Thread thread = new Thread() {
        public void run() {
            for (int i = 0; i < 10; i += 2) {
                lock.lock();
                System.out.println("hello this is thread one");
                lock.unlock();
            }
        }

    };

    // This is the second block of code
    Thread threadTwo = new Thread() {
        public void run() {
            for (int i = 0; i < 10; i += 2) {
                lock.lock();
                System.out.println("hello this is thread two");
                lock.unlock();
            }
        }

    };

    // These two statements are in the main method and begin the two
    // threads.
    // This is the third block of code
    thread.start();

    // This is the fourth block of code
    threadTwo.start();

当一个锁是公平的时候它会变得很慢,但是当它在你的第一种情况下不公平时它会在另一个线程有机会接受之前一遍又一遍地抓住锁。公平锁定就像一个队列。排队等待接下来的人得到它。

答案 2 :(得分:2)

根据CPU和/或CPU内核的数量,只有CPU可以通过在调度另一个线程之前为每个线程提供一定的时间来模拟多线程。另请参阅Wikipedia on "Preemptive Multitasking"

另外,考虑到今天的CPU和许多内核及其速度,也可能是第一个线程的执行在第二个线程开始之前已经完成。

此外,两个主题都在争夺System.out中的锁定,因此它们会相互锁定。

让线程运行更长的时间(更多的迭代次数),你会看到你期望的交错。

答案 3 :(得分:1)

你的代码也会工作......在第一个对象中睡觉。

   // This is the first block of code
        Thread thread = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i += 2) {
                    System.out.println("hello this is thread one");
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        };

答案 4 :(得分:1)

如果你想让线程的主体等到两个线程都在运行,你可以使用类似CountDownLatch的东西,它可以阻塞,直到它的内部计数器倒计数到零:

final CountDownLatch latch = new CountDownLatch(2);
Thread thread = new Thread() {
  @Override public void run() {
    latch.countDown();
    latch.await();  // Execution waits here until latch reaches zero.

    // Rest of the method.
  }
}
Thread threadTwo = new Thread() {
  @Override public void run() {
    latch.countDown();
    latch.await();  // Execution waits here until latch reaches zero.

    // Rest of the method.
  }
}

thread.start();
threadTwo.start();

(为清楚起见省略了异常处理)

这将保证两个线程的run方法的“有趣位”将同时执行。但是,由于您调用的println()方法的不正确同步,无法保证两个线程打印的消息将如何交错:

  • 有时他们可能会“完美地”交错(1,2,1,2 ......)
  • 有时可能会打印出一些没有任何东西(1,1,2,1,2,2,2 ......)
  • 有时可能会在另一个之前打印所有消息(1,1,1,1,2,2,2,2)。

答案 5 :(得分:1)

以下代码正在运作......

public class ThreadDemo {

    public static void main(String args[]) throws InterruptedException {

        // This is the first block of code
        Thread thread = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i += 2) {
                    System.out.println("hello this is thread one");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };

        // This is the second block of code
        Thread threadTwo = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i += 2) {
                    System.out.println("hello this is thread two");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };

        // These two statements are in the main method and begin the two
        // threads.
        // This is the third block of code
        thread.start();

        // This is the fourth block of code
        threadTwo.start();

    }
}

答案 6 :(得分:0)

您的代码按预期工作,绝对无法保证您的实现将以您期望的预定义方式执行。

我建议你看一下实现多线程代码的其他方法,比如join(),sleep(),找一个更适合你需要的方法。