package com.jue.test;public class ClassObject { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Thread t1 = new MyThread1("t1"); Thread t2 = new MyThread2("t2"); t2.start(); t1.start(); } static class MyThread1 extends Thread { public MyThread1(String name) { super(name); } @Override public void run() { int index = 0; while (index < 20) { index++; if (index == 10) { System.out.println(getName() + " index == 10 yield!"); yield(); } else { System.out.println(getName() + " " + index); } } } } static class MyThread2 extends Thread { public MyThread2(String name) { super(name); } @Override public void run() { int index = 0; while (index < 20) { System.out.println(getName() + " " + index); index ++; } } }}
執行結果1:
t2 0
t2 1
t2 2
t2 3
t2 4
t2 5
t2 6
t2 7
t2 8
t2 9
t2 10
t1 1
t1 2
t1 3
t1 4
t1 5
t1 6
t1 7
t1 8
t1 9
t1 index == 10 yield!
t2 11
t2 12
t2 13
t2 14
t2 15
t2 16
t2 17
t2 18
t2 19
t1 11
t1 12
t1 13
t1 14
t1 15
t1 16
t1 17
t1 18
t1 19
t1 20
執行結果2:
t1 1
t1 2
t1 3
t1 4
t1 5
t1 6
t1 7
t1 8
t1 9
t1 index == 10 yield!
t2 0
t1 11
t2 1
t1 12
t2 2
t1 13
t2 3
t1 14
t2 4
t1 15
t2 5
t1 16
t2 6
t1 17
t2 7
t1 18
t2 8
t1 19
t2 9
t1 20
t2 10
t2 11
t2 12
t2 13
t2 14
t2 15
t2 16
t2 17
t2 18
t2 19
執行結果3:
t1 1
t2 0
t1 2
t2 1
t1 3
t1 4
t1 5
t2 2
t1 6
t2 3
t1 7
t2 4
t1 8
t2 5
t1 9
t2 6
t1 index == 10 yield!
t2 7
t1 11
t2 8
t1 12
t2 9
t1 13
t2 10
t1 14
t2 11
t1 15
t2 12
t1 16
t2 13
t1 17
t2 14
t1 18
t2 15
t1 19
t2 16
t1 20
t2 17
t2 18
t2 19
執行結果4:
t2 0
t2 1
t2 2
t2 3
t2 4
t1 1
t2 5
t1 2
t2 6
t1 3
t2 7
t2 8
t1 4
t2 9
t2 10
t2 11
t1 5
t2 12
t2 13
t2 14
t1 6
t2 15
t2 16
t2 17
t1 7
t2 18
t2 19
t1 8
t1 9
t1 index == 10 yield!
t1 11
t1 12
t1 13
t1 14
t1 15
t1 16
t1 17
t1 18
t1 19
t1 20
執行結果5:
t2 0
t2 1
t2 2
t2 3
t2 4
t2 5
t2 6
t2 7
t2 8
t2 9
t2 10
t2 11
t2 12
t2 13
t2 14
t2 15
t2 16
t2 17
t1 1
t1 2
t2 18
t2 19
t1 3
t1 4
t1 5
t1 6
t1 7
t1 8
t1 9
t1 index == 10 yield!
t1 11
t1 12
t1 13
t1 14
t1 15
t1 16
t1 17
t1 18
t1 19
t1 20