java之多线程

什么是进程

进程是程序的一次执行,是系统资源分配的单位,进程包含多个线程。

真正的多线程是多个cpu,即多核,如服务器;而模拟出来的多线程只有一个cpu,一个cpu同时只能做一件事,由于切换速度非常快,人察觉不到变化,所以看上去好像是同时进行的。

如何创建线程

  • 继承Thread类,这个类本身实现了Runable接口,不建议使用,避免单继承的局限性

    public class threadDemo extends Thread{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("wq");
            }
    
        }
    }
    
  • 实现Runable接口,推荐使用,更加灵活

public class loader implements  Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("王琴");
        }

    }
}

开启线程

start()方法

 public static void main(String[] args) {
	// write your code here
        threadDemo th1=new threadDemo();
        loader l1=new loader();
        new Thread(l1).start();
        for (int i = 0; i < 100; i++) {
            System.out.println("123");
        }
        th1.start();
    }

线程停止

不建议使用stop和destroy方法

通过设立标志位让线程执行,

然后改变标志位来停止线程

public class Stopth implements Runnable{
    //线程的停止不建议使用stop和destroy方法
    //可以通过设立标志位,再改变标志位来停止
    boolean flag=true;
    @Override
    public void run() {
        while (flag){
            System.out.println("线程执行");
        }
    }
    public void stop(){
        this.flag=false;
    }
    public static void main(String[] args) {
        Stopth s=new Stopth();
        new Thread(s).start();
        for (int i = 0; i < 100; i++) {
            System.out.println("main线程"+i);
            if(i==80){
                s.stop();
                System.out.println("线程停止-------");
            }

        }
    }
}

线程休眠sleep

休眠过后的线程处于就绪状态

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

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

public class Sleepth {
    public static void main(String[] args) throws InterruptedException {
        //模拟时钟
        Date date=new Date(System.currentTimeMillis());
        while (true) {
            System.out.println(new SimpleDateFormat("hh:dd:ss").format(date));
            Thread.sleep(1000);
            date=new Date(System.currentTimeMillis());
            if(date.getSeconds()==00){
                break;
            }
        }
          //模拟倒计时
    public static void timedown() throws InterruptedException {
        int num=10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if(num==0){
                break;
            }
        }
    }
    }

线程礼让yield

礼让不会阻塞

礼让不一定成功,看cpu心情

//线程礼让,礼让不一定成功,看cpu心情
public class Yieldth implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程停止==========");
    }

    public static void main(String[] args) {
        Yieldth t=new Yieldth();
        new Thread(t,"李四").start();
        new Thread(t,"王五").start();
        //new Thread(t,"箱子").start();
    }
}

线程插队join

join方法合并线程,让其他线程阻塞,太霸道了,强行插队~~

public class Jointh implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是vip线程,请你让开~~");
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Jointh t=new Jointh();
        Thread th=new Thread(t);
        th.start();
        for (int i = 0; i <20 ; i++) {
            th.join();//vip线程插队,必须执行完vip线程,main线程才能执行
            System.out.println("我是main线程~~");
        }
    }
}

线程状态state

NEW==== 新生状态,开启前
RUNNABLE===运行,开启后
BLOCKED===阻塞
WAITING===等待,一直等
TIMED_WAITING ===定时等,为期不候
TERMINATED===终止,死亡,不能再次开启
public class Stateth {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程运行了");
        });
        thread.start();
        Thread.State state = thread.getState();
        System.out.println(state);
        while ( state!= Thread.State.TERMINATED){
            //更新线程状态
            state = thread.getState();
            System.out.println(state);
        }
    }
}

线程优先级

  • 优先级值1~10

  • 线程优先级设置,一定先设置优先级再开启线程

  • 优先级低的不一定后执行,只是执行的概率更低

  • 默认的线程优先级是5

public class Priorityth {
    public static void main(String[] args) {
        //默认线程优先级数---5,主线程一定最先执行
        System.out.println("main线程====="+Thread.currentThread().getPriority());
        myThread th=new myThread();
        Thread t1=new Thread(th);
        Thread t2=new Thread(th);
        Thread t3=new Thread(th);
        Thread t4=new Thread(th);
        Thread t5=new Thread(th);
        //先设置优先级再开启线程
        //优先级高的不一定先执行
        t1.setPriority(5);
        t1.start();
        System.out.println("main线程====="+Thread.currentThread().getPriority());
        t2.setPriority(Thread.MAX_PRIORITY);
        t2.start();
        t3.setPriority(7);
        t3.start();
        t4.setPriority(Thread.MIN_PRIORITY);
        t4.start();
        t5.setPriority(9);
        t5.start();

    }
}
class myThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"======="+Thread.currentThread().getPriority());
    }
    结果:
        main线程=====5
        main线程=====5
        Thread-4=======9
        Thread-1=======10
        Thread-3=======1
        Thread-0=======5
        Thread-2=======7

结果分析:主线程优先级不是最高的但主线程一定最先执行***

虽然设置了优先级,但并不一定优先级的高低执行,所以优先级并不是绝对的

守护线程deamon

  • 线程分为用户线程和守护线程
  • 守护线程守护着用户线程的,直到用户线程死亡,就自动停止
  • 没有设置为守护线程的都是用户线程
public class Deamonth {
    public static void main(String[] args) {
        God god=new God();
        You you=new You();
        Thread t1=new Thread(god);
        t1.setDaemon(true);//设置守护线程,默认为false
        t1.start();
        new Thread(you).start();//用户线程,没有设置为守护线程的都是用户线程
    }
}
//守护线程:守护线程守护者用户线程,直到用户线程终止才停止
class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("每天都要开开心心的,我一直都在守护,直到你离开");
        }
    }
}
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i <=30000; i++) {
            System.out.println("虽然生活艰难,但我依然坚持开心活着");
            if(i==30000){
                System.out.println("我要离开这个世界了");
                break;
            }
        }
    }
}
posted @   阿落小世界  阅读(104)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示