日期:2014-05-20  浏览次数:20838 次

今天 面试 考了 一道 线程 题 ,本人对线程 方面 不了解 请教高手
写十个线程每个线程循环加1在控制台显示出线程的名字 和加完之后得到的数

------解决方案--------------------
不知道具体什么要求,写个最简单的例子吧

Java code

class TestThread extends Thread
{
    public static int count;
    public TestThread(String name){
        super(name);
    }
    public void run(){
        //每个线程循环十次
        for(int i=0;i<10;i++){
            System.out.println(currentThread().getName()+"|| count="+count++);
        }
    }
    public static void main(String[] args) 
    {
             //十个线程
        for(int i = 0;i<10;i++){
            new TestThread("线程"+i).start();
        }
    }
}

------解决方案--------------------
那就写个带同步的例子,所谓线程同步,并不像它名字所说的那样,而是让线程排队去使用共享的资源,如何实现排队呢,就要利用同步监视器,也就相当于一把锁,这个锁必须是唯一的,一群人上厕所,只有一个坑,怎么办,按次序,谁进去之后,立刻就把锁锁上,以防后面的人趁你还没脱裤子时,就一屁股蹲坑上了。
Java code

class TestThread extends Thread
{
    public static int count ;

    public TestThread(String name){
        super(name);
    }
    public void run(){
        //线程循环十次
        for(int i = 0;i<10;i++){
            //加锁同步
            synchronized(TestThread.class){
                System.out.println(currentThread().getName()+"||count="+count++);
            }
        }
    }
    public static void main(String[] args) 
    {
        //开启十个线程
        for(int i= 0;i<10;i++){
            new TestThread("线程"+i).start();
        }
    }

}

------解决方案--------------------
再整个两个小孩交替数数的例子:
Java code

class TestThread extends Thread
{
    public static int count=1 ;
    
    public static Object obj = new Object();

    public TestThread(String name){
        super(name);
    }
    public void run(){
        synchronized(obj){
            for(int i=0;i<10;i++){
                System.out.println(currentThread().getName()+"说:我数"+count++);
                obj.notifyAll();
                try{
                    obj.wait();
                }catch(Exception e){
                    System.out.println("错误了");
                }
            }
            obj.notifyAll();
        }
    }
    

    public static void main(String[] args) 
    {
        //两个小孩
        for(int i= 1;i<3;i++){
            new TestThread("小孩"+i).start();
        }
    }

}