创建多线程的两种方式
一、继承Thread,并重写run方法,使用start方法创建线程。创建四个线程会有四个资源同时进行,如下面例子。
public class MyThread extends Thread{
	
	private int ticket=110;
	
public void run(){
		
		while(true){
			if(ticket>0){
				System.out.println(
						Thread.currentThread().getName()+"is saling ticket"+ticket--);
			}else{
				break;
			}
		}
	}
	
	public static void main(String[] args) {
		
	new MyThread().start();
	new MyThread().start();
	new MyThread().start();
	new MyThread().start();
		
	}
}
例子:
二、实现Runnable 方法,并实现run方法,start()方法创建线程,创建一个线程只会共享一个资源。
例子:
public class MyThread implements Runnable{
	
	private int ticket=110;
	
public void run(){
		
		while(true){
			if(ticket>0){
				System.out.println(
						Thread.currentThread().getName()+"is saling ticket"+ticket--);
			}else{
				break;
			}
		}
	}
	
	public static void main(String[] args) {
		MyThread t=new MyThread();
		
		t.start();
		t.start();
		t.start();
		t.start();
	}
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号