java 中的多线程 内部类实现 数据共享 和 Runnable实现数据共享

本文介绍了在Java中使用Runnable接口实现多线程的方法及优势,通过实例展示了如何利用Runnable共享数据,同时提供了通过内部类实现多线程共享数据的另一种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
java 中Runnable的好处 可以实现共享一个数据
在一个类已经从其他类派生的时候 我们不能使用 直接从Thread类派生 那么这时候我们可以通过实现Runnable
接口来实现
class Test
{
public static void main(String []args) throws Exception
{
NewThread nt=new NewThread();
new Thread(nt).start();
new Thread(nt).start();
new Thread(nt).start();
new Thread(nt).start();

while(true)
{
System.out.println(Thread.currentThread().getName()+": is run");
}

}
}


class NewThread implements Runnable
{
int index=0;
public void run()
{ while(true)

{
// System.out.println(Thread.currentThread().getName()+": is run");;
System.out.println(Thread.currentThread().getName()+":"+index++);
}

}

}
*/


/*
内部类也能实现多线程数据的共享 一般情况下我们是实现Runnable接口
*/


class Test
{
public static void main(String []args) throws Exception
{
NewThread nt=new NewThread();
nt.getThread().start();
nt.getThread().start();
nt.getThread().start();
nt.getThread().start();
while(true)
{
System.out.println(Thread.currentThread().getName()+": is run");
}

}
}

class NewThread
{
int index=0;
private class InnerThread extends Thread //设置为私有 隐藏 实现细节
{
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+":"+index++);
}
}
}
Thread getThread()
{
return new InnerThread();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值