JavaSE 基础 第57节 线程调度的三个方法

2016-07-01

package com.java1995;

import java.util.Date;

/**
 * 休眠方法sleep()
 * @author Administrator
 *
 */
public class TestSleep {
    
    public static void main(String[] args) {
        
//        for(int i=0;i<10;i++){
//            System.out.println(i);
//            try {
//                Thread.sleep(200);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
        
        while (true){
            System.out.println(new Date());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

}
package com.java1995;
/**
 * 挂起方法join()
 * @author Administrator
 *
 */
public class TestJoin {
    
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        mt.start();
        
        for(int i=0;i<10;i++){
            if(i==5){
                try {
                    mt.join();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("*********");
        }
    
    }

}

class MyThread extends Thread{
    
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("+++++++++++++++++++");
        }
    }
}
package com.java1995;
/**
 * 暂停方法yield()
 * @author Administrator
 *
 */
public class TestYield {
    
    public static void main(String[] args) {
        Thread t1=new Thread(new MyRunnable1());
        Thread t2=new Thread(new MyRunnable2());
        
        t1.start();
        t2.start();

    }

}

class MyRunnable1 implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<200;i++){
            System.out.print("+");
            Thread.yield();
        }
    }    
}

class MyRunnable2 implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<200;i++){
            System.out.print("*");
            Thread.yield();
        }
    }
}
原文地址:https://www.cnblogs.com/cenliang/p/5634269.html