多线程实现方式1:自定义一个类,继承Thread类,并重写run方法。

来源:互联网 发布:linux nmon安装 编辑:程序博客网 时间:2024/06/06 01:13
/** * 多线程实现方式1: * 自定义一个类,继承Thread类,并重写run方法。 * 线程同时运行。 * @author jiaxutianhuo * */public class XianCheng {/** * 系统默认情况下只运行主线程。 *  * @param args */public static void main(String[] args) {// main方法就是主线程//在主线程中开启两个子线程Thread1 thread1 = new Thread1();Thread2 thread2 = new Thread2();thread1.start();thread2.start();System.out.println("主线程还有3秒到达战场!");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("2...");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("1!!!");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("主线程出击!");}}/** * 线程1 *  * @author jiaxutianhuo * */class Thread1 extends Thread {/** * 线程运行期间执行的代码 */@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();System.out.println("线程1开始运行......");try {Thread.sleep(3000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("线程1继续执行......");}}class Thread2 extends Thread {/** * 线程运行期间执行的代码 */@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();System.out.println("线程2开始运行......");try {Thread.sleep(4000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("线程2继续执行......");}}

阅读全文
0 0
原创粉丝点击