您的位置:首页 >> 编程开发 >> Java >> J2SE >> 正文
J2SE RSS
 

Java之多线程(1)

http://www.rdxx.com 05年07月24日 21:14 JR 我要投稿

关键词: 多线程 , Java , 线程

                {
                    System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+
”is saling ticket”+tickets--);    //在这里有可能会打印出负数
}
}
}
}
}


同步函数
    除了可以对代码块进行同步外,也可以对函数实现同步,只要在需要同步函数定义前加上synchronized关键字即可。
class ThreadTest implements Runnable
{
    private int tickets = 100 ;
    public void run()
    {
        while(true)
        {
            sale() ;
}
}
public synchronized void sale()
{
    if(tickets>0)
    {
        try
        {    
            Thread.sleep(10) ;
}
catch(Exception e)
{
    System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+
”is saling ticket”+tickets--);
}
}
}

public class Test
{
    public static void main(String aregs[])
    {
        ThreadTest t = new ThreadTest() ;
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
    }
}


程序清单:ThreadDemo6.java
public class ThreadDemo6
{
    public static void main(String [] args)
    {
        ThreadTest t=new ThreadTest();
        new Thread(t).start();        //这个线程调用同步代码块
        t.str=new String("method"); 
        new Thread(t).start();        //这个线程调用同步函数
    }
}
class ThreadTest implements Runnable
{
    private int tickets=100;
    //同步监视
    String str = new String ("");
    public void run()
    {
        if(str.equals("method"))

共21页  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21


 
 
标签: 多线程 , Java , 线程 打印本文
 
 
  相关资讯
RSS
 
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站