通过继承Thread类实现线程与实现Runnable接口实现线程有什么区别

code小生 code小生 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
//下面这个程序是:继承线程类通过线程同步方法实现同步会出错,通过线程同步块实现同步却没有错。

//请问这二者有何区别??

class SellThread extends Thread
{
static Object obj=new Object();
static int tickets=50;
public void run()
{
while(tickets>0)
{
/*synchronized(obj)//线程同步块
{
if(tickets>0)
{
System.out.println(Thread.currentThread

().getName( )+" sell tickets:"+tickets);
tickets=tickets-1;
try
{
Thread.sleep(1);
}
catch(Exception e)
{
e.printStackTrace();
}
}*/
sell();
}
}

public synchronized void sell()//线程同步方法
{
if(tickets>0)
{
System.out.println(Thread.currentThread().getName( )+" sell

tickets:"+tickets);
tickets--;
}
}
}

class TicketsSystem_this_obj
{
public static void main(String args[])
{
SellThread st1=new SellThread();
SellThread st2=new SellThread();
SellThread st3=new SellThread();
SellThread st4=new SellThread();
st1.start();
st2.start();
st3.start();
st4.start();
/* try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}*/
}
}
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
code小生
Java SE 62,620 成员 307,251 内容