1. 程式人生 > >java——多線程的實現方式、兩種辦法解決線程賽跑

java——多線程的實現方式、兩種辦法解決線程賽跑

ble ali ide live nts nds extends sys add

多線程的實現方式:demo1、demo2

demo1:繼承Thread類,重寫run()方法

package thread_test;

public class ThreadDemo1 extends Thread {
    ThreadDemo1(){
        
    }
    ThreadDemo1(String szName){
        super(szName);
    }
    
    //重載run函數
    public void run() {
        for(int count = 1 , row = 1 ; row < 10 ; row ++ , count ++) {
            
for(int i = 0 ; i < count ; i ++) { System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { //線程賽跑 ThreadDemo1 td1 = new ThreadDemo1(); ThreadDemo1 td2 = new ThreadDemo1(); ThreadDemo1 td3
= new ThreadDemo1(); td1.start(); td2.start(); td3.start(); } }

demo2:實現runnable接口,實現run()方法

package thread_test;

public class ThreadDemo2 implements Runnable{

    public void run() {
        for(int count = 1 , row = 1 ; row < 10 ; row ++ , count ++) {
            
for(int i = 0 ; i < count ; i ++) { System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { //存在線程賽跑問題 Runnable rb1 = new ThreadDemo2(); Runnable rb2 = new ThreadDemo2(); Runnable rb3 = new ThreadDemo2(); Thread td1 = new Thread(rb1); Thread td2 = new Thread(rb2); Thread td3 = new Thread(rb3); td1.start(); td2.start(); td3.start(); } }

demo3:兩種方法解決進程賽跑問題

package thread_test;

//兩種方法解決線程賽跑
class ThreadWait extends Thread{

    public ThreadWait() {
        
    }
    
    public ThreadWait(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        for(int count = 1 , row = 1 ; row < 10 ; row ++ , count ++) {
            for(int i = 0 ; i < count ; i ++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

public class ThreadDemo3{
    public static void main(String[] args) {
        ThreadDemo3 td = new ThreadDemo3();
//        td.Method1();
        td.Method2();
    }
    
    public void Method1() {
        ThreadWait tw1 = new ThreadWait();
        ThreadWait tw2 = new ThreadWait();
        tw1.start();
        while(tw1.isAlive()) {
            try{
                Thread.sleep(100);
            }catch(Exception e){
                e.getMessage();
            }
        }
        tw2.start();
    }
    
    public void Method2() {
        ThreadWait tw1 = new ThreadWait();
        ThreadWait tw2 = new ThreadWait();
        tw1.start();
        try {
            tw1.join();
        }catch(Exception e){
            e.toString();
        }
        tw2.start();
    }
}

java——多線程的實現方式、兩種辦法解決線程賽跑