黑马程序员技术交流社区
标题:
线程通讯问题
[打印本页]
作者:
刘宣超
时间:
2014-9-12 21:41
标题:
线程通讯问题
线程通讯问题
创建两个线程 分别依次给数组里面随机存放int数据
要求两个线程轮流存放各存放3次。
自己做了半天做成这样,也不知道还思路对不对。
求解答
import java.awt.Robot;
import java.util.Random;
public class Demo4{
final static shareArray1 sh = new shareArray1();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i<3 ; i++){
try {
sh.Thread1(new Random().nextInt());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i<3;i++){
try {
sh.Thread1(new Random().nextInt());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
class shareArray1{
private static int[] sum = new int[6];
private static int n=0;
private static boolean badge = true;
public synchronized void Thread1(int i) throws InterruptedException{
while(!badge)
this.wait();
sum[n] = i;
System.out.print(Thread.currentThread().getName());
System.out.println(sum[n]);
n++;
Thread.sleep(3000);
badge = false;
this.notifyAll();
}
public synchronized void Thread2(int i) throws InterruptedException{
while(badge)
this.wait();
sum[n] = i;
System.out.print(Thread.currentThread().getName());
System.out.println(sum[n]);
n++;
Thread.sleep(3000);
badge = true;
this.notifyAll();
}
}
作者:
The_king丶
时间:
2014-9-13 08:37
不注释好难看···
作者:
谢建平
时间:
2014-9-13 10:26
匿名内部部看着就不舒服 0.0 还不如直接定义个类方便阅读
作者:
darkads
时间:
2014-9-13 10:32
这个就是售票模型
线程对共享数据对象加锁,一个线程执行一次存入操作,使用加锁对象的notify()唤醒另一个线程,然后使用加锁对象的wait()方法使当前线程陷入沉睡
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2