`
coolszy
  • 浏览: 1407084 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

多线程简单实例

阅读更多

在Java程序中创建多线程有两种方法:继承Thread类和实现Runnable接口

 

1.继承Thread类

import java.lang.*;

public class Demo
{
	public static void main(String[] args)
	{
		MyThread thread=new MyThread("Hello");
		thread.start();
	}
}

class MyThread extends Thread
{
	public MyThread(String name)
	{
		super(name);  //给线程命名
	}
	public void run()
	{
		System.out.println("线程"+getName()+"开始了。");
	}
}

 

 

2.实现Runnable接口

import java.lang.*;

public class Demo
{
	public static void main(String[] args)
	{
		MyThread thread=new MyThread();
		new Thread(thread,"Hello").start();
	}
}

class MyThread implements Runnable
{
	public void run()
	{
		//因为不是继承Thread类,因此必须先调用currentThread方法
		System.out.println("线程"+Thread.currentThread().getName()+"开始了");
	}
}

 

    使用Runnable接口的好处不仅在于间接解决了多继承问题,与Thread类相比,Runnable接口更适合于多线程处理同一资源。

 

分享到:
评论
1 楼 xiaoliang330 2011-02-19  
 

相关推荐

Global site tag (gtag.js) - Google Analytics