Java学习,多线程

来源:互联网 发布:scala map json 编辑:程序博客网 时间:2024/05/29 03:40

JAVA中,从语言层次上就支持多线程,多线程的同步和互斥可以使用wait 和 notify来解决。需要注意的是wait和notify所对应的等待队列必须是同一对象的。现在学习多线程对我来说还是太早了,先了解这么多吧!

生产者消费者问题:

class Test
{
    
public static void main(String[] args)
    {
        Queue q
=new Queue();
        Producer p
=new Producer(q);
        Consumer c
=new Consumer(q);
        p.start();
        c.start();
    }
}

class Producer extends Thread
{
    Queue q;
    Producer(Queue q)
    {
        
this.q=q;
    }
    
public void run()
    {
        
for(int i=0;i<10;i++)
        {
            q.put(i);
            System.out.println(
"Producer put "+i);
        }
    }
}
class Consumer extends Thread
{
    Queue q;
    Consumer(Queue q)
    {
        
this.q=q;
    }
    
public void run()
    {
        
while(true)
        {
            System.out.println(
"Consumer get "+q.get());
        }
    }
}
class Queue
{
    
int value;
    
boolean bFull=false;
    
public synchronized void put(int i)
    {
        
if(!bFull)
        {
            value
=i;
            bFull
=true;
            notify();
        }
        
try
        {
            wait();
        }
        
catch(Exception e)
        {
            e.printStackTrace();
        }
            
    }
    
public synchronized int get()
    {
        
if(!bFull)
        {
            
try
            {
                wait();
            }
            
catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        bFull
=false;
        notify();
        
return value;
    }
}