Java线程示例? [英] Java Thread Example?

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

问题描述

有没有人能以简单的方式提供一个解释Java Threads的示例程序?例如,假设我有三个线程 t1 t2 t3 。我想要一个代码来演示线程同时执行,而不是按顺序执行。

Could anyone give an example program that explains Java Threads in a simple way? For example, say I have three threads t1, t2 and t3. I want a code that demonstrates that the threads execute simultaneously, and not sequentially.

推荐答案

这是一个简单的例子:

ThreadTest.java

public class ThreadTest
{
   public static void main(String [] args)
   {
      MyThread t1 = new MyThread(0, 3, 300);
      MyThread t2 = new MyThread(1, 3, 300);
      MyThread t3 = new MyThread(2, 3, 300);

      t1.start();
      t2.start();
      t3.start();
   }
}

MyThread.java

public class MyThread extends Thread
{
   private int startIdx, nThreads, maxIdx;

   public MyThread(int s, int n, int m)
   {
      this.startIdx = s;
      this.nThreads = n;
      this.maxIdx = m;
   }

   @Override
   public void run()
   {
      for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
      {
         System.out.println("[ID " + this.getId() + "] " + i);
      }
   }
}

还有一些输出:

[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23

解释 - 每个 MyThread 对象尝试打印0到300之间的数字,但它们只负责该范围的某些区域。我选择按索引拆分它,每个线程跳过总线程数。所以 t1 确实索引0,3,6,9等。

An explanation - Each MyThread object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1 does index 0, 3, 6, 9, etc.

现在,没有IO,琐碎的计算就像这仍然可以看起来就像线程正在顺序执行一样,这就是为什么我只显示输出的第一部分。在我的计算机上,在ID 10的输出线程一次完成后,接着是9,然后是8.如果你输入等待或收益,你可以更好地看到它:

Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:

MyThread.java

System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();

输出:

[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7

现在你可以看到每个线程都在执行,提前放弃控制,下一次执行。

Now you can see each thread executing, giving up control early, and the next executing.

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

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