zoukankan      html  css  js  c++  java
  • 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();
    
    
        }
    }
  • 相关阅读:
    第二章.md
    第四章.md
    第一章.md
    第九章.md
    png简析.md
    第五章.md
    好看的粒子效果
    缓动 减速运动
    收集的小效果
    粒子效果2
  • 原文地址:https://www.cnblogs.com/wwyx-xi/p/7527462.html
Copyright © 2011-2022 走看看