- package MyThread;
- public class ThreadOne {
- public static void main(String[] args) {
- Res r = new Res();
- Producer p = new Producer(r);
- Consumer c = new Consumer(r);
- Thread t1 = new Thread(p);
- Thread t2 = new Thread(p);
-
- Thread t3 = new Thread(c);
- Thread t4 = new Thread(c);
- Thread t5 = new Thread(c);
-
- t1.start();
- t2.start();
-
- t3.start();
- t4.start();
- t5.start();
- }
- }
- class Res{
- private String name;
- private int id;
- private boolean flag = false;
-
- public synchronized void Pro(String name){
-
- while(flag)
- {
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- this.name = name+":"+id++;
-
- System.out.println(Thread.currentThread().getName()+"-------我是生产者-------"+this.name);
- flag = true;
- this.notifyAll();
- }
- public synchronized void Con(){
- while(!flag)
- {
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName()+"..我是消费者..."+name);
- flag = false;
- this.notifyAll();
- }
-
- }
- class Producer implements Runnable
- {
-
- Res r;
- Producer(Res r){
- this.r = r;
- }
- @Override
- public void run() {
-
- while(true){
- r.Pro("+商品");
- }
- }
- }
- class Consumer implements Runnable{
- Res r;
- Consumer(Res r){
- this.r = r;
- }
-
- @Override
- public void run() {
- while(true){
- r.Con();
- }
-
- }
-
- }
复制代码
这是代码,在eclipse上运行就会死机,用cmd编译并运行就没事,这是为什么呢? |
|