多线程的使用

package cm.aichijihua;

public class ThreadTest1 {
	

	public static void main(String[] args) {
		
		
		// 方式1 重写线程的run()方法 将要执行的方法写run方法中
		Thread thread = new Thread(){
			@Override
			public void run() {
				
				while (true) {
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
					
					System.out.println(Thread.currentThread().getName());
					System.out.println(this.getName());
				}
				
			}
		};
		thread.start();
		
		
		// 方式2 重写线程的方法,将需要执行的代码传入到Runable对象的run方法中 相对于第一种方法
		// 第二种方法更符合面向对象的思维逻辑, 因为真的调用run方法的是Runable对象 
		Thread thread2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				while (true) {
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName());
				}
				
			}
		});
		thread2.start();
		
		
		// 要是重写了父类的方法,就先调用重写的父类方法,父类的方法没有重写,那么调用Runable类的run方法
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while (true) {
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
					System.out.println("第二种方式");
				}
				
			}
		}){
			public void run() {
				while (true) {
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
					System.out.println("第一种方式");
				}
			};
		}.start();
		
	}
	
}

猜你喜欢

转载自huxinyao1016.iteye.com/blog/2306220