我的博客

创建多线程的两种方式

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

  

posted @ 2017-12-28 16:17  孤雁11  阅读(180)  评论(0编辑  收藏  举报