java中的多线程

一个java程序实际上是一个JVM进程,JVM进程用一个主线程来执行main()方法,在main()方法内部,我们又可以启动多个线程。此外,JVM还有负责垃圾回收的其他工作线程等。

第一种:继承Thread类

public class MyThread{
    public static void main(String[] args) {
        final Thread t = new testThread();
        t.start(); // 启动新线程
        System.out.println("start main thread!");

        
    }
}

class testThread extends Thread {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}

运行测试

package pack_10;

public class testThread {
    public static void main(String[] args) {
        System.out.println("main start...");
        Thread t = new Thread() {
            public void run() {
                System.out.println("thread run...");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {}
                System.out.println("thread end.");
            }
        };
        t.start();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {}
        System.out.println("main end...");
    }
}

运行结果

注意:调用run()方法和调用start()是不一样的!

public class MyThread{
    public static void main(String[] args) {
        final Thread t = new testThread();
        t.start(); // 启动新线程,start为同时执行
        for (int i = 0; i < 10; i++) {
            System.out.println("start main thread!");
        }
    }
}

class testThread extends Thread {
    @Override
    public void run() {
         for (int i = 0; i < 10; i++) {
            System.out.println("start run thread!");
        }
    }
}

输出结果:

可以看到上述是交替执行的。因此,调用普通方法例如调用run()方法是普通调用,会先执行run方法,依然是主线程执行,而调用start方法则会开起子线程,从此主线程和子线程会并行交替执行。

第二种方法:通过runnable接口实现多线程

package com.lipu.demo01;

//创建线程方式2:现实重写runnable接口,重写run方法,执行线程需要丢入runnable接口实现类
public class TestThread03 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println("我在看代码。。。"+i);

        }
    }
    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread03 testThread03=new TestThread03();
        //创建线程对象,通过线程对象来开启我们的线程,代理 简单理解通过Thread实现runnable接口
//        Thread thread=new Thread(testThread03);
//        thread.start();
        new Thread(testThread03).start();
        for (int i = 0; i < 200; i++) {
            System.out.println("我在学习多线程。。。"+i);

        }
    }

}
原文地址:https://www.cnblogs.com/lipu12281/p/12187342.html