Java中join和yield的作用

     

                                本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处!

      

   1、   A.join,在API中的解释是,堵塞当前线程B,直到A执行完毕并死掉,再执行B。

用一个小例子来说明吧

static class ThreadA extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			for (int i = 0; i < 10; i++) {
				System.out.println("ThreadA" + i);
			}
		}
	}

	static class ThreadB extends Thread {
		ThreadA a;

		public ThreadB(ThreadA a) {
			// TODO Auto-generated constructor stub
			this.a = a;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			System.out.println("ThreadB start");
			try {
				a.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("ThreadB end");
		}
	}

	public static void main(String[] args) {
		ThreadA a = new ThreadA();
		ThreadB b = new ThreadB(a);
		b.start();
		a.start();
	}

执行结果:

ThreadB start
ThreadA0
ThreadA1
ThreadA2
ThreadA3
ThreadA4
ThreadA5
ThreadA6
ThreadA7
ThreadA8
ThreadA9
ThreadB end

首先b线程执行,a线程join后,直接执行完a,然后才执行b,证实上述说法。

2、A.yield,A让出位置,给B执行,B执行结束A再执行。跟join意思正好相反!

	static class ThreadA extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			for (int i = 0; i < 10; i++) {
				System.out.println("ThreadA " + i);
			}
		}
	}

	static class ThreadB extends Thread {
		ThreadA a;

		public ThreadB(ThreadA a) {
			// TODO Auto-generated constructor stub
			this.a = a;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			System.out.println("ThreadB start");
			try {
				for (int i = 0; i < 10; i++) {
					if(i==2){
						a.yield();
					}
					System.out.println("ThreadB " + i);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("ThreadB end");
		}
	}

	public static void main(String[] args) {
		ThreadA a = new ThreadA();
		ThreadB b = new ThreadB(a);
		b.start();
		a.start();
	}

执行结果:

ThreadB start
ThreadA 0
ThreadB 0
ThreadA 1
ThreadB 1
ThreadA 2
ThreadB 2
ThreadB 3
ThreadB 4
ThreadB 5
ThreadB 6
ThreadB 7
ThreadB 8
ThreadB 9
ThreadB end
ThreadA 3
ThreadA 4
ThreadA 5
ThreadA 6
ThreadA 7
ThreadA 8
ThreadA 9

首先B执行,然后A执行;在B的循环中,i=2时,A执行yield;接着B执行完,才轮到A执行。



你可能感兴趣的:(JOIN,线程)