简单网页设计主题,罗湖网站建设公司乐云seo,seo建站还有市场吗,织梦html5网站模板目录
一.线程创建
1.方法#xff08;1#xff09;继承Thread来创建一个线程类
2.方法(2)实现 Runnable 接⼝
3.方法#xff08;3#xff09;匿名内部类创建 Thread ⼦类对象
二.线程的中断
三.线程等待
4.线程休眠 一.线程创建
Java 中的线程#xff08;Thread1继承Thread来创建一个线程类
2.方法(2)实现 Runnable 接⼝
3.方法3匿名内部类创建 Thread ⼦类对象
二.线程的中断
三.线程等待
4.线程休眠 一.线程创建
Java 中的线程Thread是一种轻量级的子进程用于执行程序中的一段代码。线程的使用可以实现程序的并发执行提高程序的运行效率。在 Java 中线程的基本用法涉及线程的创建、中断、等待、休眠以及获取线程实例等操作。
1.方法1继承Thread来创建一个线程类
class MyThread extends Thread{public void run(){System.out.println(这里是线程运行的代码);}
}public class Test {public static void main(String[] args) {MyThread myThread new MyThread(); //创建MyThread类的实例myThread.start(); //调用start方法启动线程}
}2.方法(2)实现 Runnable 接⼝
class MyThread extends Thread{public void run(){System.out.println(这里是继承Thread类的代码);}
}class MyRunable implements Runnable{ //继承Thread来创建一个线程类public void run(){System.out.println(这是实现Runable接口的代码);}
}public class Test {public static void main(String[] args) {MyThread myThread new MyThread();Thread t new Thread(new MyRunable()); //创建 Thread 类实例, 调⽤ //Thread 的构造⽅法时将 //Runnable 对象作为 target 参数.myThread.start();t.start(); //调⽤ start ⽅法启动线程}
}
3.方法3匿名内部类创建 Thread ⼦类对象
Thread t1 new Thread() {Overridepublic void run() {System.out.println(使⽤匿名类创建 Thread ⼦类对象);}
};
lambda 表达式创建 Runnable ⼦类对象 Thread t4 new Thread(()-{System.out.println(使⽤匿名类创建 Thread ⼦类对象);});
二.线程的中断
通过调用interrupt()方法来中断
public class Test {public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(()-{int count 0;while (!Thread.currentThread().isInterrupted()){System.out.println(count);count;}});t1.start();Thread.sleep(1000);t1.interrupt();}
}
在上述代码中通过 Thread.currentThread().isInterrupted() 来检查线程的中断状态。如果线程未被中断则继续执行耗时操作否则退出循环。
三.线程等待
有时我们需要等待⼀个线程完成它的⼯作后才能进⾏⾃⼰的下⼀步⼯作我们使用join()方法来进行
public class Test {public static void main(String[] args) throws InterruptedException {//Object locker new Object();for (int i 0; i 10; i) {Thread t1 new Thread(()- {System.out.print(A);});Thread t2 new Thread(()-{System.out.print(B);});Thread t3 new Thread(()-{System.out.println(C);});t1.start();t1.join();t2.start();t2.join();t3.start();t3.join();}}}
上述代码中在t1执行完后再执行t2在t2执行完后再执行t3按照顺序打印出ABC,大家可以试试把join注释掉看看运行的结果
4.线程休眠
线程休眠是一种使线程暂停执行一段时间的机制可以通过调用 sleep() 方法来实现。
public class Test {public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(()-{int count 0;while (true){System.out.println(count);count;try {Thread.sleep(1000); //休眠1秒} catch (InterruptedException e) {throw new RuntimeException(e);}}});t1.start();}
}在上述代码中每次打印一次count都会暂停一秒让后在继续打印