多线程编程面试题

public class ABC_Condition {
    private static Lock lock=new ReentrantLock();
    private static Condition con1=lock.newCondition();
    private static Condition con2=lock.newCondition();
    private static Condition con3=lock.newCondition();
    
    private static int count=0;
    static class ThreadA extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for(int i=0;i<10;i++) {
                    while(count%3==0) {
                        con1.await();
                        System.out.println("A");
                        count++;
                        con2.signal();
                    }
                }
            }catch(InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    
    static class ThreadB extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for(int i=0;i<10;i++) {
                    while(count%3==1) {
                        con2.await();
                        System.out.println("B");
                        count++;
                        con3.signal();
                    }
                }
            }catch(InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    
    static class ThreadC extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for(int i=0;i<10;i++) {
                    while(count%3==2) {
                        con3.await();
                        System.out.println("C");
                        count++;
                        con1.signal();
                    }
                }
            }catch(InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
        
    }
}
    
public class ABC_Lock {
    private static Lock lock=new ReentrantLock();
    private static int state=0;
    
    static class ThreadA extends Thread{
        @Override
        public void run() {
            for(int i=0;i<10;i++) {
                try {
                    lock.lock();
                    while(state%3==0) {
                        System.out.println("A");
                        state++;
                        i++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    
    static class ThreadB extends Thread{
        @Override
        public void run() {
            for(int i=0;i<10;i++) {
                try {
                    lock.lock();
                    while(state%3==1) {
                        System.out.println("B");
                        state++;
                        i++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    
    static class ThreadC extends Thread{
        @Override
        public void run() {
            for(int i=0;i<10;i++) {
                try {
                    lock.lock();
                    while(state%3==2) {
                        System.out.println("C");
                        state++;
                        i++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    
    public static void main(String[] args) {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
    }
}

public class ConductAndConsume {
    public static void main(String[] args) {
        Student s=new Student();
        SetStudent ss=new SetStudent(s);
        GetStudent gs=new GetStudent(s);
        Thread t1=new Thread(ss,"生产者");
        Thread t2=new Thread(gs,"消费者");
        t1.start();
        t2.start();
        
}
}

class Student{
    private String name;
    private int age;
    boolean flag;
    
    //生产者的功能,为student对象赋值
    public synchronized void set(String name,int age) {
        if(this.flag) {
            try {
                this.wait();
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name=name;
        this.age=age;
        this.flag=true;
        this.notify();
    }
    //消费者的功能,打印student对象
    public synchronized void get() {
        if(!this.flag) {
            try {
                this.wait();
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name+"  "+age);
        this.flag=false;
        this.notify();
    }
}
class SetStudent implements Runnable{
    private Student s;
    private int x=0;
    public SetStudent(Student s) {
        this.s=s;
    }
    @Override
    public void run() {
        while(true) {
            if(x%2==0) {
                s.set("zhangsan", 11);
            }else {
                s.set("lisi", 22);
            }
            x++;
        }
        
    }
}

class GetStudent implements Runnable{
    private Student s;
    public GetStudent(Student s) {
        this.s=s;
    }
    @Override
    public void run() {
        while(true) {
            s.get();
        }
        
    }
}
//设计四个线程,其中两个线程每次对变量i加1,另外两个线程每次对i减1
public class FourProcessAddSub{
    private int i=0;
    public static void main(String[] args) {
        FourProcessAddSub fp=new FourProcessAddSub();
        Add add=fp.new Add();
        Sub sub=fp.new Sub();
        for(int i=1;i<=2;i++) {
            new Thread(add,"线程"+i).start();
            new Thread(sub,"线程"+i).start();
        }
    }


public synchronized void addOne() {
    i++;
    System.out.println(Thread.currentThread().getName()+"+1的值为:"+i);
}
public synchronized void subOne() {
    i--;
    System.out.println(Thread.currentThread().getName()+"-1的值为:"+i);
}
class Add implements Runnable {

    @Override
    public void run() {
        for(int i=0;i<10;i++) {
            addOne();
            try {
                Thread.sleep(100);
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
  
}

class Sub implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<10;i++) {
            subOne();
            try {
                Thread.sleep(100);
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
}
}
//子线程循环10次,主线程循环20次,接着子线程循环10次,主线程循环20次...如此反复循环50次
public class Function {
    private boolean flag=false;
    
    Lock lock=new ReentrantLock();
    Condition con=lock.newCondition();
    
    public void sub() {
        lock.lock();
        try {
            while(flag) {
                try {
                    con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }       
        }
            for(int i=0;i<10;i++) {
                System.out.println("sub:"+i);
            }
            flag=true;
            con.signal();
            }finally {
            lock.unlock();
        }
        
    }
    public synchronized void main() {
        lock.lock();
        try {
            while(!flag) {
                try {
                    con.await();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            for(int i=0;i<20;i++) {
                System.out.println("main"+i);
            }
            flag=false;
            con.signal();
        }finally {
            lock.unlock();
        }
    }
    
    

}

//用3个线程打印递增的数
public class PrintNum3Process {
    public static void main(String[] args) {
        final Handler handler=new Handler();
        for(int i=0;i<3;i++) {
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    for(int j=0;j<5;j++) {
                        handler.print(Thread.currentThread().getName());
                    }
                    
                }
            },i+"").start();
        }
    }
}
class Handler{
    private int num=1;
    private int status=0;
    
    public synchronized void print(String nums) {
        int Index=Integer.parseInt(nums);
        while(Index!=status) {
            try {
                this.wait();
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print("Thread"+nums+":");
        for(int count =0;count<5;count++,num++) {
            if(count>0) {
                System.out.print(",");
            }
            System.out.print(num);
        }
        System.out.println();
        status=(status+1)%3;
        this.notifyAll();
    }
}

//两个线程交替打印1-100
public class PrintOneTOHundred implements Runnable {
    //设置一个全局变量,两个线程先后访问这个变量
    int i=1;
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true) {
            synchronized(this) {
                notify();
                try {
                    Thread.currentThread().sleep(100);
                }catch(InterruptedException e) {
                    e.printStackTrace();
                }
                if(i<=100) {
                    System.out.println(Thread.currentThread().getName()+":"+i);
                    i++;
                    try {
                        wait();
                    }catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    public static void main(String[] args) {
        PrintOneTOHundred p=new PrintOneTOHundred();
        Thread t1=new Thread(p);
        Thread t2=new Thread(p);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}

//交替打印a1b2c3d4
public class PrintTwoNum {
 static final Object object=new Object();
 public static void main(String[] args) {
    new Thread(new Runnable() {
        String a[]= {"a","b","c","d"};
        @Override
        public void run() {
            for(int i=0;i<4;i++) {
                synchronized(object) {
                    object.notify();
                    try {
                        object.wait();
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(a[i]);
                    object.notify();
                }
            }
            
        }
    }).start();
    new Thread(new Runnable() {
        int a[]= {1,2,3,4};
        @Override
        public void run() {
            for(int i=0;i<4;i++) {
                synchronized(object) {
                    object.notify();
                    try {
                        object.wait();
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(a[i]);
                    
                }
            }
        }
    }).start();
}
}

/*
 * 现有的程序代码模拟产生了16个日志对象,
 * 并且需要运行16秒,才能打印完这些日志,
 * 请在程序中增加4个线程去调用parseLog()方法来分头打印这16个日志对象,
 * 程序只需要运行4秒即可打印完这些日志对象
 */
public class ProcessLog {
    public static void main(String[] args) {
        final BlockingQueue<String> quene=new ArrayBlockingQueue<>(16);
        for(int i=0;i<4;i++) {
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    while(true) {
                        try {
                            parseLog(quene.take());
                        }catch(InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    
                }
            }).start();
        }
        System.out.println("begin:"+(System.currentTimeMillis()/1000));
        for(int i=0;i<16;i++) {
            final String log=" "+(i+1);
            {
                try {
                    quene.put(log);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void parseLog(String log) {
        System.out.println(log+":"+System.currentTimeMillis()/1000);
        try {
            Thread.sleep(1000);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容