Java进阶知识查漏补缺01

创建线程的方式一:

package com.cjf.Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Everything
 * Date: 2020-07-01
 * Time: 12:06
 */

//多线程的创建方式一:: 继承于Thread类
//         1.创建一个继承于Thread类的子类
//         2.重写Thread类的run() --> 将此线程执行的操作声明在run()中
//         3.创建Thread类的子类的对象
//         4.通过此对象调用start()

class MyThread extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2==0){
                System.out.println("子线程:"+i);
            }
        }
    }
}

public class ThreadTest{
    public static void main(String[] args) {//主线程
//        3.创建Thread类的子类的对象
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
//         4.通过此对象调用start()
        t1.start();//1.启动当前线程;2.调用当前线程的run()
        t2.start();
        for (int i = 0; i < 100; i++) {
            if (i%2==0){
                System.out.println("main线程:"+i);
            }
        }

    }
}

创建线程的方式二:

package com.cjf.Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Everything
 * Date: 2020-07-01
 * Time: 16:43
 */

//创建多线程的方式二:实现Runnable接口
//    1.创建一个实现了Runnable接口的类
//    2.实现类去实现Runnable中的抽象方法: run()
//    3.创建实现类的对象
//    4.将此对象作为参数传递到Thread类的构造器中,创建Thread 类的对象
//    5.通过Thread 类的对象调用start()

class Mthread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2==0){
                System.out.println("子线程:"+i);
            }
        }
    }
}


public class ThreadTest1 {
    public static void main(String[] args) {

        Mthread mthread1 = new Mthread();
        Thread thread1 = new Thread(mthread1);
        thread1.start();
        //启动线程,调用了当前的线程的run(),等价于调用了Runnable类型的target
        //因为Thread(Runnable target),这个有参构造器也可以实现这个Runable

        for (int i = 0; i < 100; i++) {
            if (i%2==0){
                System.out.println("主线程:"+i);
            }
        }

    }
}

 

posted @ 2020-07-01 23:40  Tsui98'  阅读(141)  评论(0编辑  收藏  举报