java多線程--實現Runnable接口方式

由於java類只能繼承一個類能夠實現多個接口的特性,因此通常狀況下不推薦使用繼承Thread類實現多線程,下面是實現Runnable接口方式的簡單多線程代碼

package text;

/**
 * 多線程
 * @author admin
 *
 */
public class Threads {
    
    public static void main(String[] args){
        Thread_1 t1=new Thread_1();
        Thread thread1 =new Thread(t1);
        thread1.start();
        
        Thread_2 t2 =new Thread_2();
        Thread thread2=new Thread(t2);
        thread2.start();
        
    }
}
    
class Thread_1 implements Runnable{
    
    public void run() {
        try {
            //線程暫停一秒
            Thread.sleep(1000); 
            System.out.println("執行方法1");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
            
    }
}

class Thread_2 implements Runnable{
    
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println("執行方法2");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
    }    
}
    

循環java

package test.bean;

public class xc {
     
     public static  void main(String[] args){
         for(int i = 0 ; i < 10 ; i ++ ){
             test t = new test();
             new Thread(t).start();
         }
     }
}
class test implements Runnable{
    public void run() {
        System.out.println("線程:"+Thread.currentThread().getName() + "執行");    
    }  
}
相關文章
相關標籤/搜索