您的位置:首页 > 编程语言 > Java开发

Java Thread Join方法

2011-08-30 21:03 477 查看
In this segment of tutorial we will learn how to use the join method in the Thread.Then We will create an example of Thread with the use of join method.

Java Join method join the next thread at the end of the currentthread
After current thread stops execution then next thread executes.

public class join implements Runnable {

@Override
public void run() {
for (int x = 1; x <= 3; x++) {
System.out.println("this is thread "
+ Thread.currentThread().getName());
}
}

public static void main(String[] args) throws Exception {
join j1 = new join();
Thread t1 = new Thread(j1, "1");
Thread t2 = new Thread(j1, "2");
Thread t3 = new Thread(j1, "3");
t1.start();
t1.join();
t2.start();
t3.start();
}
}


Output :

this is thread 1this is thread 1this is thread 1this is thread 3this is thread 2this is thread 2this is thread 2this is thread 3this is thread 3

可以在t2.start后面再 加个t2.join()看看区别。

再列个例子:

using System;

namespace TestThreadJoin

{

class Program

{

static void Main()

{

System.Threading.Thread x = new System.Threading.Thread(new System.Threading.ThreadStart(f1));

x.Start();

Console.WriteLine("This is Main.{0}", 1);

x.Join();

Console.WriteLine("This is Main.{0}", 2);

Console.ReadLine();

}
static void f1()

{

System.Threading.Thread y = new System.Threading.Thread(new System.Threading.ThreadStart(f2));

y.Start();

y.Join();

Console.WriteLine("This is F1.{0}",1);

}

static void f2()

{

Console.WriteLine("This is F2.{0}", 1);

}

}

}
这儿有三个线程在处理(包括主线程),大家可看看执行结果.
结果:
This is Main.1
This is F2.1
This is F1.1
This is Main.2
如果: 注释// x.Join();
结果:
This is Main.1
This is Main.2
This is F2.1
This is F1.1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: