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

java线程Thread和Runnable区别和联系

    博客分类:
  • Java
阅读更多
我们都晓得java实现线程2种方式,一个是继承Thread,另一个是实现Runnable。

模拟窗口买票,第一例子继承thread,代码如下
package thread;

public class ThreadTest {
	
	public static void main(String[] args) {
		
		Thread1 t1 = new Thread1("01");
		Thread1 t2 = new Thread1("03");
		t1.start();
		t2.start();
		
		//可以看出一共卖了200张票
	}
}

class Thread1 extends Thread{
	
	private int ticket = 100;
	
	public Thread1(String name)
	{
		super(name);
	}
	
	@Override
	public void run() {
		while(ticket > 0)
		{
			System.out.println("窗口:"+Thread.currentThread().getName()+",卖了1个,剩余:"+(ticket--));
		}
	}
}


模拟窗口买票,实现Runnable接口,代码如下
package thread;

public class RunnableTest {
	
	public static void main(String[] args) {
		
		Runnable1 r1 = new Runnable1();
		
		new Thread(r1, "01").start();
		new Thread(r1, "03").start();
		
		//2个窗口一共卖了100张
	}

}

class Runnable1 implements Runnable
{
	private int ticket = 100;
	
	@Override
	public void run() {
		while(ticket > 0)
		{
			System.out.println("窗口:"+Thread.currentThread().getName()+",卖了1个,剩余:"+(ticket--));
		}
	}
}


通过上面代码运行我们可以得到如下结论:

1.Thread和Runnable都可以实现多线程(废话)
2.Thread是类,而Runnable是接口,这就是类和接口区别,类只能继承一次,而接口可以实现多个接口。
3.Thread实现Runnable接口,这个可以查看Thread的源代码。
4.最重要的分享资源功能,一般我们使用多线程就是快速解决资源问题。Runnable可以实现资源分享,类实现Runnable并不具备线程功能,必须通过new Thread(runabble子类)调用start()启动线程,所以我们通常new一个runnable的子类,启动多个线程解决资源问题。Thread是类所以我们每次new一个对象时候资源已经实例化了,不能资源共享,Thread类要实现资源共享,可以声明变量为static,类共享的可以解决。
5.通过以上建议最好实现Runnable接口 实现多线程。


欢迎交流企鹅群:211367604
30
17
分享到:
评论
5 楼 zx_code 2015-06-23  
focus2008 写道
两个线程存在数据竞争,尽然不用锁?

肯定要用,这只是写的测试案例而已
4 楼 zx_code 2015-06-23  
bassda 写道
Thread t = new Thread1();
Thread t1 = new Thread(t,"01"); 
Thread t2 = new Thread(t,"03"); 
t1.start(); 
t2.start(); 
这样写就能共享了,实际上和Runnable没什么区别。

是的,可以的
3 楼 bassda 2015-06-20  
Thread t = new Thread1();
Thread t1 = new Thread(t,"01"); 
Thread t2 = new Thread(t,"03"); 
t1.start(); 
t2.start(); 
这样写就能共享了,实际上和Runnable没什么区别。
2 楼 focus2008 2015-06-20  
两个线程存在数据竞争,尽然不用锁?
1 楼 cywhoyi 2015-06-19  
join()

相关推荐

Global site tag (gtag.js) - Google Analytics