首页 > 编程语言 > 详细

创建多线程的两种方式

时间:2017-12-28 17:03:50      阅读:205      评论:0      收藏:0      [点我收藏+]

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

  

创建多线程的两种方式

原文:https://www.cnblogs.com/story1/p/8136283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!