---
title: "多线程--join和yield"
author: "uusoft"
date: "2011-10-02T09:08:45Z"
tags: []
categories: ["编程语言"]
slug: "join-yield"
draft: false
lastmod: "2011-10-02T09:08:45Z"
id: 1184445
url: "https://uusoft.iteye.com/blog/1184445"
---

```java
//A线程遇到B线程join A线程让出执行权 直到B线程执行完毕再执行
public class JoinDemo 
{
	public static void main(String[] args) throws Exception
	{
		Demo d=new Demo();
		Thread t1=new Thread(d);
		Thread t2=new Thread(d);
		t1.setName("t1");
		t2.setName("t2");
		t1.start();
		//t1.join();
		t2.start();
		t1.join();
		for(int i=0;i<80;i++)
		{
			System.out.println("main----------"+"  i="+i);
		}
	}
}


class Demo implements Runnable
{
	public void run()
	{
		for(int i=0;i<50;i++)
		{
			System.out.println(Thread.currentThread().getName()+"  i="+i);
		}
	}
}

```



线程调用yield后暂停执行权

```java
class YieldDemo 
{
	public static void main(String[] args) 
	{
		Demo d=new Demo();
		Thread t1=new Thread(d);
		Thread t2=new Thread(d);
		t1.start();
		t2.start();

	}
}


class Demo implements Runnable
{
	public void run()
	{
		for(int i=0;i<100;i++)
		{
			Thread.yield();
			System.out.println(Thread.currentThread().getName()+"..."+i);
		}
	}
}
```