多线程编程面试题

2018-10-29  本文已影响0人  冰与河豚鱼
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();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读