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();
        }
        
    }    
}
    

循环

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() + "执行");    
    }  
}

 

转载于:https://www.cnblogs.com/angto64/p/5126585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值