Java线程示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2531938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Thread Example?
提问by JavaUser
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.
谁能给出一个示例程序,以简单的方式解释 Java 线程?例如,假设我有三个线程t1
,t2
和t3
。我想要一个代码来演示线程同时执行,而不是按顺序执行。
采纳答案by Phil
Here is a simple example:
这是一个简单的例子:
ThreadTest.java
线程测试.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);
}
}
}
And some output:
还有一些输出:
[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
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.
解释 - 每个MyThread
对象都尝试打印 0 到 300 之间的数字,但它们只负责该范围的某些区域。我选择按索引拆分它,每个线程按线程总数向前跳跃。这样t1
做索引0,3,6,9,等
Now, without IO, trivial calculations like this can still looklike 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:
现在,如果没有 IO,像这样的琐碎计算仍然看起来像线程在按顺序执行,这就是为什么我只显示输出的第一部分。在我的电脑上,这个 ID 为 10 的输出线程一次全部完成后,接着是 9,然后是 8。如果你放入一个等待或一个产量,你可以更好地看到它:
MyThread.java
我的线程
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
和输出:
[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.
现在您可以看到每个线程都在执行,提前放弃控制权,然后执行下一个线程。
回答by Tim Bender
There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.
无论其他人发布的任何简单示例如何,都不能保证您的线程同时执行。如果您的操作系统只为 Java 进程提供一个处理器来处理,您的 Java 线程仍将以循环方式为每个时间片安排。这意味着,不会有两个同时执行,但他们所做的工作将是交错的。您可以使用 Java 的 Visual VM(JDK 中的标准)等监控工具来观察 Java 进程中执行的线程。
回答by Sahil Jain
A simple example:
一个简单的例子:
public class Test extends Thread {
public synchronized void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("i::"+i);
}
}
public static void main(String[] args) {
Test obj = new Test();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Thread t3 = new Thread(obj);
t1.start();
t2.start();
t3.start();
}
}
回答by abd alkojok
create java application in which you define two threads namely t1 and t2, thread t1 will generate random number 0 and 1 (simulate toss a coin ). 0 means head and one means tail. the other thread t2 will do the same t1 and t2 will repeat this loop 100 times and finally your application should determine how many times t1 guesses the number generated by t2 and then display the score. for example if thread t1 guesses 20 number out of 100 then the score of t1 is 20/100 =0.2 if t1 guesses 100 numbers then it gets score 1 and so on
创建 Java 应用程序,在其中定义两个线程,即 t1 和 t2,线程 t1 将生成随机数 0 和 1(模拟抛硬币)。0 表示头部,1 表示尾部。另一个线程 t2 将执行相同的 t1 并且 t2 将重复此循环 100 次,最后您的应用程序应确定 t1 猜测 t2 生成的数字的次数,然后显示分数。例如,如果线程 t1 从 100 个数字中猜出 20 个数字,那么 t1 的分数是 20/100 =0.2 如果 t1 猜出 100 个数字,那么它的分数为 1,依此类推