Java- 如何实现多线程?


1、继承Thread 类,重写run 方法

public class TestCreateThread{
    public static void main(String args[]){
        MyThread t = new MyThread();
        t.start();
        for(int i = 0;i<100;i++){
            System.out.println("main");
        }
    }
    
}

class MyThread extends Thread{
    public void run(){
        for(int i = 0;i<100;i++){
            System.out.println("thread");
        }
        
    }

}

2、实现runnable 接口,实现run() 方法

public class TestCreateThread{
    public static void main(String args[]){
        MyThread1 t1 = new MyThread1();
        t1.start();
        
        MyThread2 r = new MyThread2();
        Thread t2 = new Thread(r);
        t2.start();
        
        for(int i = 0;i<1000;i++){
            System.out.println("Main");
        }
    }
}

class MyThread1 extends Thread{
    public void run(){
        for(int i = 0;i<1000;i++){
            System.out.println("Thread");
        }
        
    }

}

class MyThread2 implements Runnable{
    public void run(){
        for(int i = 0;i<1000;i++){
            System.out.println("Runnable");
        }
    }
}

3、实现 Callable 接口,重写call() 方法

不太会

 

 

ps.注意的是 线程对象不要直接调run()方法。直接调,run()就是普通方法,实现多线程,需要调start()方法,然后由jvm 去调用run()方法。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM