多线程实现方式的思路及代码实现(Runnable接口)

package cn.itcast_01;
/*
 * 方式2:实现Runnable接口
 * 步骤:
 *    A:自定义MyRunnable实现Runnable接口
 *    B:重写run()方法
 *    C:创建MyRuannable的对象
 *    D:创建T和read类的对象,并把C步骤的对象作为参数传递
 */
public class 多线程方式2的思路及代码实现 {
    
    

	public static void main(String[] args) {
    
    
		//创建MyRunnable的对象
		MyRunnable my = new MyRunnable();
        
		
		//创建T和read类的对象,并把C步骤的对象作为参数传递
		//Thread(Ruannable target)
//		Thread t1 =new Thread(my);
//		Thread t2 =new Thread(my);
//		
//		t1.setName("打开更加方便");
//		t2.setName("哦华丰国货");
		
		Thread t1 = new Thread(my,"第十八肯德基");
		Thread t2 = new Thread(my,"阿克苏巨化股份");
		
		t1.start();
		t2.start();
	}
}
public class MyRunnable implements Runnable {
    
    
	@Override
	public void run() {
    
    
	    for(int x =0;x<100;x++) {
    
    
	    	//由于实现接口的方式就不能直接使用Thread类的方法了,但是可以间接的使用
	    	System.out.println(Thread.currentThread().getName()+"-----"+x);    	
	    }
	}
}

猜你喜欢

转载自blog.csdn.net/kaszxc/article/details/108913512