如何迅速创建龙岗区住房和建设局网站的广州网站服务?
摘要:广州网站快速制作,龙岗区住房和建设局网站,优秀的营销策划案例,计算机培训班学什么文章目录 一、线程的启动1.1 start()方法 二、线程的休眠与中断2.1 Thread.sleep()方法2.2 interrupt()方法 三、线程的等
广州网站快速制作,龙岗区住房和建设局网站,优秀的营销策划案例,计算机培训班学什么文章目录 一、线程的启动1.1 start()方法 二、线程的休眠与中断2.1 Thread.sleep()方法2.2 interrupt()方法 三、线程的等待与唤醒3.1 wait()方法3.2 Object类的notify()和notifyAll()方法3.3 await()和signal()方法3.4 使用join()方法等待线程执行完成 四、线程的状态控制与管… 文章目录 一、线程的启动1.1 start()方法 二、线程的休眠与中断2.1 Thread.sleep()方法2.2 interrupt()方法 三、线程的等待与唤醒3.1 wait()方法3.2 Object类的notify()和notifyAll()方法3.3 await()和signal()方法3.4 使用join()方法等待线程执行完成 四、线程的状态控制与管理4.1 线程的优先级设置4.2 线程的守护与非守护状态 五、其他常用的线程操作方法5.1 使用yield()方法让出CPU资源5.2 使用isAlive()方法判断线程是否存活 一、线程的启动
1.1 start()方法 无论是通过继承Thread类还是实现Runnable接口线程的启动都需要调用start()方法。
// 定义一个实现Runnable接口的自定义线程类
public class MyRunnable implements Runnable {Overridepublic void run() {// 线程执行的代码逻辑}
}// 在主线程中创建并启动自定义线程
public class Main {public static void main(String[] args) {// 创建线程对象Thread thread new Thread(new MyRunnable());// 启动线程thread.start();}
}二、线程的休眠与中断
2.1 Thread.sleep()方法
Thread.sleep()方法用于使当前线程休眠一段时间。它接受一个以毫秒为单位的参数表示线程休眠的时间调用这个方法必须要声明或捕捉异常。 try {// 线程休眠2秒Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(线程休眠结束);2.2 interrupt()方法 Thread类的interrupt()方法用于中断线程。当一个线程被中断时它的中断状态将被设置为true默认是 flase设置后不一定真的中断看jvm如何选择我们把握不了。 调用中断方法也要声明或捕捉异常InterruptedException 可以通过Thread类的isInterrupted()方法来检查线程的中断状态。
public class MyThread implements Runnable {Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println(线程执行中);}System.out.println(线程被中断);}
}public class Main {public static void main(String[] args) {// 创建线程对象Thread thread new Thread(new MyThread());// 启动线程thread.start();// 中断子线程try {thread.interrupt();} catch (InterruptedException e) {e.printStackTrace();}}
}三、线程的等待与唤醒 线程的等待与唤醒是多线程编程中常用的一种机制它允许线程在满足特定条件之前等待然后在条件满足时被唤醒继续执行。Java提供了多种方式来实现线程的等待与唤醒。
3.1 wait()方法 Object类中的wait()方法用于使当前线程等待并释放当前线程持有的锁。wait()方法需要在synchronized块内部调用以确保线程在等待前释放锁。 调用wait方法使线程进入等到状态后不会自动醒过来需要手动让线程苏醒。
