多线程编程

2020-08-11  本文已影响0人  昵乄称

创建线程

  1. 创建线程的三种方式
创建方式
Thread class 继承Thread类(重点)
Runnable 接口 实现Runnable接口(重点)
Callable 接口 实现Callable接口(了解)

Thread创建线程

public class ThreadStudy extends  Thread {
    @Override
    public void run() {
        //super.run();
        for (int i = 0; i < 200; i++) {
            System.out.println("测试线程======="+i);
        }
    }

    public static void main(String[] args) {
        //创建一个线程对象
        ThreadStudy threadStudy = new ThreadStudy();
        //调用start()方法,开启线程
        threadStudy.start();
        for (int i = 0; i < 10000; i++) {
            System.out.println("学习线程=========="+i);
        }
    }
}

ps:线程开启不一定立即执行,由cpu调度执行

Runable 创建线程

/**
 * 创建线程方法二:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类
 * 推荐使用runnable接口,java单继承的局限性
 */
public class StudyRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println("测试线程**********************"+i);
        }
    }

    public static void main(String[] args) {
        StudyRunnable studyRunnable = new StudyRunnable();
        new Thread(studyRunnable).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("主线程*******************"+i);
        }
    }
}

小结:

继承Thread类

实现Runable接口

线程状态

线程休眠:

Thread.sleep(1000);
  1. sleep(时间)指定当前线程阻塞的毫秒数

  2. sleep存在异常InterruptedException;

  3. sleep时间达到后线程进入就绪转态

  4. sleep可以模拟网络延时,倒计时等

  5. 每个对象都有一个锁,sleep不会释放锁

    public class SleepThread {
        //时间倒计时
        public static void main(String[] args) {
            Date date = new Date(System.currentTimeMillis());//获取当前系统时间
            while (true){
                try {
                    Thread.sleep(1000); //阻塞线程1000毫秒也就是1秒
                    System.out.println(new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(date));
                    date =  new Date(System.currentTimeMillis()); //更新系统时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    输出:

    2020:08:10 16:36:21
    2020:08:10 16:36:22
    2020:08:10 16:36:23
    2020:08:10 16:36:24
    2020:08:10 16:36:25
    2020:08:10 16:36:26
    2020:08:10 16:36:27
    2020:08:10 16:36:28
    2020:08:10 16:36:29
    2020:08:10 16:36:30
    2020:08:10 16:36:31 
    

线程礼让:

yield()方法:表示当前线程对象提示调度器自己愿意让出CPU资源,但是调度器可以自由忽略

在开发中一般不会用到该方法,只在调试或测试的时候用

public class StudyRunnable implements Runnable {
    public void run() {
        System.out.println("测试线程**********************");

    }

    public static void main(String[] args){
        StudyRunnable studyRunnable = new StudyRunnable();
        new Thread(studyRunnable).start();
        Thread.yield();
        System.out.println("主线程*******************");
    }
}

输出:

测试线程**********************
主线程*******************

线程强制执行(JOIN):

public class ThreadJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("vip线程来了"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadJoin threadJoin = new ThreadJoin();
        Thread thread = new Thread(threadJoin);
        
        thread.start();
        //主线程
        for (int i = 0; i < 500; i++) {
            if(i == 20){
                thread.join();//插队
            }
            System.out.println("测试线程"+i);
        }
    }
}

线程优先级:

public class ThreadJoin implements Runnable {
    @Override
    public void run() {
            System.out.println(Thread.currentThread().getName()+"***"+"vip线程来了");
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadJoin threadJoin = new ThreadJoin();
        Thread thread1= new Thread(threadJoin,"最低优先级");
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread1.start();

        Thread thread2= new Thread(threadJoin,"最高优先级");
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread2.start();

        Thread thread3= new Thread(threadJoin,"中间优先级");
        thread3.setPriority(Thread.NORM_PRIORITY);
        thread3.start();
        
        System.out.println(thread1.getPriority());
        System.out.println(thread2.getPriority());
        System.out.println(thread3.getPriority());

    }
}

输出:

最高优先级***vip线程来了
中间优先级***vip线程来了
最低优先级***vip线程来了
1
10
5
//优先级 优先级高的先执行
//线程默认优先级为5
Thread.MIN_PRIORITY=1
Thread.MAX_PRIORITY=10
Thread.NORM_PRIORITY=5
getPriority(),setPriority(int xxx); 改变线程的优先级

优先级的设定建议在start()调度前

ps.优先级低只是意味着获得调度的概率低,并不是低优先级就不会被调度,都是看CPU的调度

线程分类:

User和Daemon两者几乎没有区别,唯一的不同之处就在于虚拟机的离开:

public class TestSynchronized  {
    public static void main(String[] args) {
        Tiktok tiktok = new Tiktok(10);
        Thread t1 = new Thread(tiktok,"小赵");
        Thread t2 = new Thread(tiktok,"小钱");
        Thread t3 = new Thread(tiktok,"小孙");
        Thread t4 = new Thread(tiktok,"小李");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class Tiktok implements Runnable{
    private int tickenum;
    private boolean flag = true;
    public Tiktok(int tickenum) {
        this.tickenum = tickenum;
    }
    @Override
    public void run() {
        while (flag){
            try {
                moth();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }        
    }
    public synchronized void moth() throws InterruptedException {
        if(tickenum<=0){
            flag =false;
            return;
        }
        Thread.sleep(500);
        System.out.println(Thread.currentThread().getName()+"\t 号码为:"+tickenum--);
    }
}
上一篇下一篇

猜你喜欢

热点阅读