1. 程式人生 > >創建多線程的兩種方式

創建多線程的兩種方式

nts system main getname 共享 gpo name xtend class

一、繼承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();
	}

  

創建多線程的兩種方式