java 核心编程——线程之线程控制(五)

1.线程运行状态图

2.线程的启动(start)和停止(stop)

package se.thread;

import java.util.Date;

public class ThreadController1 extends Thread {

    int count = 0;

    @Override
    public void run() {

        while(true){

            System.out.println(count+++":"+new Date());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {

        ThreadController1 threadController1 = new ThreadController1();
        threadController1.start();

        //主线程休息4秒后关闭子线程

        try {
            Thread.sleep(4000);
            threadController1.stop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

3.线程的休眠和挂起

  yield()方法和sleep()方法的区别;

  相同点:都能使线程阻塞挂起

       不同点:1.yield不能设置阻塞时间  2:yield只能使相同优先级的线程有机会运行。

package se.thread;

public class ThreadSleep  extends  Thread{


    @Override
    public void run() {

        for (int i = 0; i < 10 ; i++) {
            if(i == 5 && Thread.currentThread().getName().equals("test1")){
                Thread.yield();
            }

            System.out.println(Thread.currentThread().getName()+":"+i);
        }

    }

    public static void main(String[] args) {


        ThreadSleep threadSleep1 = new ThreadSleep();
        ThreadSleep threadSleep2 = new ThreadSleep();

        Thread test1 = new Thread(threadSleep1,"test1");
        Thread test2 = new Thread(threadSleep2,"test2");

        test1.start();
        test2.start();

    }

}

4.线程的同步synchronized

  线程执行过程中必须考虑与其他线程之间共享数据或者协调状态。

package se.thread;

public class ThreadSync extends  Thread {

    @Override
    public void run() {
    synchronized (this) {
        for (int i = 0; i < 10; i++) {

            System.out.println(Thread.currentThread().getName() + ":" + i);

        }
    }


    }

    public static void main(String[] args) {

        ThreadSync threadSync = new ThreadSync();
        ThreadSync threadSync1 = new ThreadSync();

        Thread t1 = new Thread(threadSync,"test1");
        Thread t2 = new Thread(threadSync1,"test2");


        t1.start();
        t2.start();


    }
}

 

posted @ 2017-09-15 17:23  柳暗花明睡一觉  阅读(173)  评论(0)    收藏  举报