JAVA 核心笔记 || [3] 修饰符

JAVA 多线程

JAVA多线程: 最大限度的利用CPU 并行执行程序的多个部分

创建线程的两种方法
  • 扩展 Thread 类
  • 实现 Runnable 接口

扩展 Thread 类 创建多线程

ThreadLearn.java

public class ThreadLearn extends Thread{
    public void run(){
        try{
            System.out.println(
                "Thread id="+
                Thread.currentThread().getId() +
                "   Thread name="+
                Thread.currentThread().getName()
            );

        }catch(Exception e){
            System.out.println(
                e
            );
        }

    }
}

EnterThread.java

public class EnterThread{
    public static void main(String[] args){
        byte count = 10;
        for(byte i=0; i< count; i++){
            ThreadLearn tl = new ThreadLearn();
            tl.start();
        }
    }
}

运行

Thread id=10   Thread name=Thread-0
Thread id=13   Thread name=Thread-3
Thread id=12   Thread name=Thread-2
Thread id=11   Thread name=Thread-1
Thread id=15   Thread name=Thread-5
Thread id=14   Thread name=Thread-4
Thread id=16   Thread name=Thread-6
Thread id=17   Thread name=Thread-7
Thread id=18   Thread name=Thread-8
Thread id=19   Thread name=Thread-9

实现 Runnable 接口创建多线程

RunnableLearn.java

public class RunnableLearn implements Runnable{

    private Thread t;

    public RunnableLearn(){
    }

    public void run(){
        try{
            System.out.println(
                "Runnable Thread id = "+
                Thread.currentThread().getId()+
                " Runnable Thread name = "+
                Thread.currentThread().getName()
            );
        }catch(Exception e){
            System.out.println( e );
        }
    }

    public void start(){
        t = new Thread(this);
        t.start();
    }
}

EnterThreadj.java

public class EnterThread{
    public static void main(String[] args){
        byte count = 10;
        /*
        for(byte i=0; i< count; i++){
            ThreadLearn tl = new ThreadLearn();
            tl.start();
        }
        */

        for(byte j=0; j

运行

Runnable Thread id = 10 Runnable Thread name = Thread-0
Runnable Thread id = 14 Runnable Thread name = Thread-4
Runnable Thread id = 13 Runnable Thread name = Thread-3
Runnable Thread id = 12 Runnable Thread name = Thread-2
Runnable Thread id = 11 Runnable Thread name = Thread-1
Runnable Thread id = 16 Runnable Thread name = Thread-6
Runnable Thread id = 15 Runnable Thread name = Thread-5
Runnable Thread id = 18 Runnable Thread name = Thread-8
Runnable Thread id = 17 Runnable Thread name = Thread-7
Runnable Thread id = 19 Runnable Thread name = Thread-9

你可能感兴趣的:(JAVA 核心笔记 || [3] 修饰符)