2020-03-14(pm) · 线程的创建和使用

一,练习题一:

先用之前学到的线程创建方式一完成

package com.atguigu.java;

/**
 * @anthor shkstart
 * @create 2020-03-14-21:20
 */

class test1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2 == 0){
                System.out.println("偶数:" + i);
            }
        }
    }
}

class test2 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2 != 0){
                System.out.println("奇数:" + i);
            }
        }
    }
}

public class AllTest {
    public static void main(String[] args) {
        test1 tt1 = new test1();
        test2 tt2 = new test2();

        tt1.start();
        tt2.start();
    }
}
可以优化的方案:

把四个步骤糅合到一起。

package com.atguigu.java;

/**
 * @anthor shkstart
 * @create 2020-03-14-21:20
 */

//class test1 extends Thread {}
//
//class test2 extends Thread {}

public class AllTest {
    public static void main(String[] args) {

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        System.out.println("偶数:" + i);
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 != 0) {
                        System.out.println("奇数:" + i);
                    }
                }
            }
        }.start();
    }
}



二,Thread 类的一些常用方法

  1. start():启动当前线程:调用当前线程的run()。
  2. run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法体里。
  3. currentThread():静态方法,返回执行当前代码的线程。
  4. getName():获取当前线程的名字。
  5. setName():设置当前线程的名字。
  6. yield():释放当前cpu的执行权。
  7. join():在线程a中调用线程b的join(),此时线程a就暂停。直到线程b完全执行完以后,线程a才继续执行。
  8. stop():已过时。当执行此方法是,强制结束当前线程。
  9. sleep(long millitime):让当前线程暂停指定的millitime毫秒。在指定的millitime毫秒时间内, 当前线程是阻塞(暂停)状态的。
  10. isAlive():判断当前线程是否存活。
package com.atguigu.java;

/**
 * @anthor shkstart
 * @create 2020-03-14-21:20
 */

class test1 extends Thread {
    //2.run():通常需要重写Thread类中的此方法,
    //将创建的线程要执行的操作声明在此方法体里
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                //9.sleep(long millitime):让当前线程暂停指定的millitime毫秒。
                //在指定的millitime毫秒时间内,当前线程是阻塞(暂停)状态的。
//                try {
//                    sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }


                //3.currentThread():静态方法,返回执行当前代码的线程
                //4.getName():获取当前线程的名字
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }

            //6.yield():释放当前cpu的执行权
//            if (i%20 == 0){
//                this.yield();
//            }

        }
    }
}


public class AllTest {
    public static void main(String[] args) {

        test1 tt1 = new test1();

        //5.setName():设置当前线程的名字
        tt1.setName("线程一");

        //1.start():启动当前线程:调用当前线程的run()
        tt1.start();

        //5.setName():设置当前线程的名字
        Thread.currentThread().setName("主线程");
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }

            //7.join():在线程a中调用线程b的join(),此时线程a就暂停。
            // 直到线程b完全执行完以后,线程a才继续执行。
//            if (i == 20) {
//                try {
//                    tt1.join();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }

        }

        //10.isAlive():判断当前线程是否存活。
//       System.out.println(tt1.isAlive());
    }
}



三、线程的优先级问题

  1. 线程的优先级等级:
    --MAX_PRIORITY (10)
    --MIN _PRIORITY (1)
    --NORM_PRIORITY(5)
  2. 涉及的方法:
    --getPriority() :返回线程优先值。
    --setPriority(int newPriority) :改变线程的优先级。
  3. 说明:
    --线程创建时继承父线程的优先级。
    --低优先级只是获得调度的概率低,并非一定是在高优先级线程之后才被调用。
package com.atguigu.java;

/**
 * @anthor shkstart
 * @create 2020-03-14-21:20
 */

class test1 extends Thread {
    //2.run():通常需要重写Thread类中的此方法,
    //将创建的线程要执行的操作声明在此方法体里
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                //9.sleep(long millitime):让当前线程暂停指定的millitime毫秒。
                //在指定的millitime毫秒时间内,当前线程是阻塞(暂停)状态的。
//                try {
//                    sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }


                //3.currentThread():静态方法,返回执行当前代码的线程
                //4.getName():获取当前线程的名字
                System.out.println(Thread.currentThread().getName() + ":"
                        // getPriority():获取线程的优先级
                        + Thread.currentThread().getPriority() + ":" + i);
            }

            //6.yield():释放当前cpu的执行权
//            if (i%20 == 0){
//                this.yield();
//            }

        }
    }
}


public class AllTest {
    public static void main(String[] args) {

        test1 tt1 = new test1();

        //5.setName():设置当前线程的名字
        tt1.setName("线程一");

        //setPriority(int p):设置线程的优先级(p:1 ~ 10)
        tt1.setPriority(Thread.MAX_PRIORITY);
//        tt1.setPriority(10);

        //1.start():启动当前线程:调用当前线程的run()
        tt1.start();

        //5.setName():设置当前线程的名字
        Thread.currentThread().setName("主线程");
        //setPriority(int p):设置线程的优先级(p:1 ~ 10)
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":"
                        // getPriority():获取线程的优先级
                        + Thread.currentThread().getPriority() + ":" + i);
            }

            //7.join():在线程a中调用线程b的join(),此时线程a就暂停。
            // 直到线程b完全执行完以后,线程a才继续执行。
//            if (i == 20) {
//                try {
//                    tt1.join();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }

        }

        //10.isAlive():判断当前线程是否存活。
//       System.out.println(tt1.isAlive());
    }
}



四、关于本章的所有代码:

package com.atguigu.java;

/**
 * 测试Thread中的常用方法:
 * 1.start():启动当前线程:调用当前线程的run()
 * 2.run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法体里
 * 3.currentThread():静态方法,返回执行当前代码的线程
 * 4.getName():获取当前线程的名字
 * 5.setName():设置当前线程的名字
 * 6.yield():释放当前cpu的执行权
 * 7.join():在线程a中调用线程b的join(),此时线程a就暂停。
 *           直到线程b完全执行完以后,线程a才继续执行。
 * 8.stop():已过时。当执行此方法是,强制结束当前线程。
 * 9.sleep(long millitime):让当前线程暂停指定的millitime毫秒。在指定的millitime毫秒时间内,
 *                          当前线程是阻塞(暂停)状态的。
 * 10.isAlive():判断当前线程是否存活。
 *
 *
 * 线程的优先级:
 * 1.
 * MAX_PRIORITY :10
 * MIN _PRIORITY :1
 * NORM_PRIORITY :5  -->默认的优先级
 * 2.如何设置和获取当前线程的优先级
 *     getPriority():获取线程的优先级
 *     setPriority(int p):设置线程的优先级(p:1 ~ 10)
 *
 *    说明:高优先级的线程要抢占低优先级线程cpu的执行权。
 *         但是这不表示只有高优先级的线程执行完以后,低优先级才可以执行。
 *         1~10也只是概率大小问题。
 *
 *
 * @anthor c.c.
 * @create 2020-03-14-14:19
 */
public class ThreadMethodTest {
    public static void main(String[] args) {
        HelloThread h1 = new HelloThread("Thread①");

        //设置线程的名称
//        h1.setName("线程一");

        //设置分线程的优先级
        h1.setPriority(Thread.MAX_PRIORITY);

        //开始线程
        h1.start();

        //给主线程命名(先获取该线程)
        Thread.currentThread().setName("主线程");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        for (int i = 0; i < 100; i++) {
            if (i%2 == 0){
                System.out.println(Thread.currentThread().getName() + ":"
                        + Thread.currentThread().getPriority() + ":" + i);
            }

//            if (i == 20) {//有问题就alt+enter
//                try {
//                    h1.join();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
        }

        //判断线程是否存活
//        System.out.println(h1.isAlive());
    }
}


class HelloThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2 == 0){

                //让线程进入睡眠,相当于暂停,可以设置暂停时间
//                try {
//                    sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

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

            //看第7点
//            if (i % 20 == 0){
//                this.yield();
//            }
        }


    }


    public HelloThread(String name){//通过构造器的方式,给线程命名
        super(name);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 7,186评论 1 15
  • 林炳文Evankaka原创作品。转载自http://blog.csdn.net/evankaka 本文主要讲了ja...
    ccq_inori阅读 3,865评论 0 4
  • Java多线程学习 [-] 一扩展javalangThread类 二实现javalangRunnable接口 三T...
    影驰阅读 8,064评论 1 18
  • 一、进程和线程 进程 进程就是一个执行中的程序实例,每个进程都有自己独立的一块内存空间,一个进程中可以有多个线程。...
    阿敏其人阅读 7,395评论 0 13
  • 1 线程概念 1.1 进程 在现代的操作系统中,进程是资源分配的最小单位,而线程是CPU调度的基本单位。 一个进程...
    凯玲之恋阅读 4,518评论 0 0