您的位置:首页 > 编程语言 > Java开发

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

2011-08-02 20:28 423 查看
/*

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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: