Java笔记14 线程2

本文介绍了Java中线程的基本操作,包括设置线程名字、获取当前线程、线程的优先级控制,以及线程的休眠、让步和join方法的使用。同时提到了线程同步的概念,强调了线程安全在多线程编程中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Thread的常用方法

  • public final void setName(String name); 设置当前线程的名字;
  • public static Thread currentThread(); 返回对当前正在执行的线程对象的引用;
  • public final String getName(); 返回当前线程的名字;
class test extends Thread{
    public void run(){
        System.out.println("分支线程");
        System.out.println(Thread.currentThread().getName()+"在执行");
    }
}
public class TestThread {
    public static void main(String[] args) {
        test t=new test();
        t.start();
        System.out.println("主线程");
        System.out.println(Thread.currentThread().getName()+"在执行");
    }
}

在这里插入图片描述

二、线程的控制

  1. 优先级控制
  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程线程调度器按照线程的优先级决定应调度哪个线程来执行。
  • 线程的优先级用数字表示。范围从1到10,一个线程的缺省优先级是5。
Thred.MIN PRIORITY = 1
Thread.MAX PRIORITY = 10
Thread.NORM PRIORITY = 5
  • 可以使用下述线方法获得或设置线程对象的优先级。
    int getPriority();
    void setPriority(int newPriority);
  • 通常高优先级的线程将先于优先级低的线程执行,但并不总是这样,因此实际开发中并不单纯依赖优先级来决定线程运行次序。
public class TestPriority {
    public static void main(String[] args) {
        Thread t1=new Thread(new TP1());
        Thread t2=new Thread(new TP2());
        t1.setPriority(Thread.NORM_PRIORITY);
        System.out.println("t1.getPriority():"+t1.getPriority()+"\n"+"t2.getPriority():"+t2.getPriority());
        t1.start();
        t2.start();
    }
}
class TP1 implements Runnable{
    public void run(){
        for (int i = 0; i < 10; i++) {
            System.out.println("P1:"+i);
        }
    }
}
class TP2 implements Runnable{
    public void run(){
        for (int i = 0; i < 10; i++) {
            System.out.println("P2:"+i);
        }
    }
}

在这里插入图片描述
在这里插入图片描述

  1. 线程的休眠和让步
  • 线程休眠:暂停执行当前运行中的线程,使之进入阻塞状态,待经过指定的“延迟时间”后再醒来并转入到就绪状态。
  • Thread类提供的相关方法:
    public static void sleep(long millis)
    public static void sleep(long millis, int nanos)
  • 由于是静态方法,可以由Thread直接调用;
  • sleep()方法会抛出InterruptedException异常,我们必须得对其进行捕捉;
class test0 extends Thread{
    public void run(){
        System.out.println("分支线程");
        System.out.println(Thread.currentThread().getName()+"在执行");
        try {
            Thread.sleep(100);  //执行完上一步语句就暂停100毫秒
        } catch (InterruptedException e) {
            //e.printStackTrace();
            System.out.println(e);
        }
    }
}

class Tset1 implements Runnable{
//无论是继承Thread类的run方法还是实现Runnable接口的run方法,都不能抛出任何异常
    public void run() //throws Exception
    {
        for (int i = 0; i < 100; i++) {
            System.out.println("Tset1:"+i);
        }
    }
}

class Tset2 implements Runnable{
    public void run(){
        for (int i = 0; i < 100; i++) {
            System.out.println("Tset2:"+i);
        }
    }
}

public class TestThread {
    public static void main(String[] args) {
        test0 t=new test0();
        Thread t1=new Thread(new test0());
        t1.start();
        t.start();
        try {
            Thread.sleep(12);  //12毫秒
        } catch (InterruptedException e) {
            //e.printStackTrace();
        }
        System.out.println("主线程");
        System.out.println(Thread.currentThread().getName()+"在执行");
    }
}

在这里插入图片描述

  • 线程的让步:public static void yield()
  1. 让出CPU,给其他线程执行的机会;
  2. 让运行中的线程主动放弃当前获得的CPU 处理机会,但不是使该线程阻塞,而是使之转入就绪状态。
public class TestThread {
    public static void main(String[] args) {
        MyThread1 mt=new MyThread1();
        Thread t1=new Thread(mt);
        Thread t2=new Thread(mt);
        t1.setName("线程A");
        t2.setName("线程B");

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

        System.out.println("主线程");
        System.out.println(Thread.currentThread().getName()+"在执行");
    }
}
class MyThread1 implements Runnable{
    public void run(){
        //遇到3的倍数必定切换,且大概率是人为造成的切换;
        // 非3的倍数的切换一定是系统自动的切换
        for (int i = 0; i <= 6; i++) {
            System.out.println(Thread.currentThread().getName()+"在执行");
            if(0==i%3){//每执行到3的倍数 就进入一次就绪状态,另一个线程就开始执行
                System.out.println("线程"+Thread.currentThread().getName()+"让步,使其处于就绪状态");
                Thread.yield();//让出CPU,当前线程进入就绪队列等待调度。
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

  • join的使用
public class TestJoin {
    public static void main(String[] args) {
        MyRunner r = new MyRunner();
        Thread t = new Thread();
        t.start();
        try {
            t.join();
            //暂停当前正在执行 t.join(); 的线程,
            //直到t所对应的线程运行终止之后,当前线程才会获得继续执行的机会
            //注意: t.join()不是暂停t对象所对应的线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 6; i++) {
            System.out.println("主线程:" + i);
        }
    }
}

class MyRunner implements Runnable {
    public void run() {
        for (int i = 0; i < 6; i++) {
            System.out.println("子线程:" + i);
        }
    }
}

在这里插入图片描述

  1. 挂起和恢复
  • 线程挂起:暂时停止当前运行中的线程,使之转入阻塞状态,并且不会自动恢复运行;
  • 线程恢复使得一个已挂起的线程恢复运行;
  • Thread类提供的相关方法:
    public final void suspend();
    public final void resume();
  • suspend() 方法挂起线程时并不释放其锁定的资源,这可能会影响其他线程的运行,且容易导致线程的死锁,已不提倡使用
  1. 线程的串行化
  2. 生命周期控制
    在这里插入图片描述
    执行完t.start();后并不表示t所对象的线程就一定会立即得到执行,t.start();执行完后只是表示 t 线程具有了可以立即被CPU执行的资格,但由于想抢占CPU执行的线程很多,CPU并不一定会立即去执行 t 所应的线程
  • 结束一个进程:
public class TestShutThread {
    public static void main(String[] args) {
        S0 aa = new S0();
        Thread tt = new Thread(aa);
        tt.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        aa.shutDown();
    }
}

class S0 implements Runnable {
    private boolean flag = true;

    public void run() {
        while (flag) {
            System.out.println("AAAA");
        }
    }

    public void shutDown() {
        this.flag = false;
    }
}

在这里插入图片描述

  1. 线程的同步
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值