zoukankan      html  css  js  c++  java
  • Java多线程面试题--保证多个线程顺序执行

    public class A implements Runnable {
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		System.out.println("A");
    	}
    
    }
    
    public class B implements Runnable {
    
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		System.out.println("B");
    	}
    
    }
    
    public class C implements Runnable {
    
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		System.out.println("C");
    	}
    
    }
    
    /**
    	 * 方法一:
    	 * @param args
    	 * @throws InterruptedException
    	 */
    	public static void main(String[] args) throws InterruptedException {
    		// TODO Auto-generated method stub
    		Thread thread1 = new Thread(new A());
    		thread1.start();
    		thread1.join();
    		Thread thread2 = new Thread(new B());
    		thread2.start();
    		thread2.join();
    		Thread thread3 = new Thread(new C());
    		thread3.start();
    	}
    

      使用join()方法,等前一个线程执行完毕,下一个线程才能执行

    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 保证多个线程顺序执行
     * @author 尘世间迷茫的小书童
     *
     */
    public class TestJoin {
        
        public static void main(String[] args) {
            
            List<Thread> threads = new ArrayList<>();
            
            for(int i=0; i<100; i++) {
                threads.add(new Thread(() -> {
                    System.out.println(Thread.currentThread().getName());
                }, "线程"+i));
            }
            
            threads.forEach(thread -> {
                thread.start();
                try {
                    thread.join(); //具体实现调用Object wait方法
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            
        }
        
    }
    /**
    	 *    方法二:
    	 */
    	@Test
    	public void test2() {
    		//创建只有一根线程的线程池
    		ExecutorService executorService = Executors.newSingleThreadExecutor();
    		executorService.submit(new A());
    		executorService.submit(new B());
    		executorService.submit(new C());
    		executorService.shutdown();
    	}
    

      创建一个只有一根线程的线程池,保证所有任务按照指定顺序执行

    /**
     * 线程顺序执行类
     * @author 15735400536
     *
     */
    public class StepOver {
    	
    	private volatile int count = 1;
    	
    	public void a() throws InterruptedException {
    		synchronized (this) {
    			while(count != 1) {
    				wait();
    			}
    			System.out.println("线程A");
    			count = 2;
    			notifyAll();
    			
    //			if(count == 1) {
    //				System.out.println("线程A");
    //				count = 2;
    //				//Thread.currentThread().notifyAll();
    //				notifyAll();
    //			}else {
    //				//Thread.currentThread().wait(1000);
    //			    wait();
    //			}
    		}
    	}
    	
    	public void b() throws InterruptedException {
    		synchronized (this) {
    			while(count != 2) {
    				wait();
    			}
    			System.out.println("线程B");
    			count = 3;
    			notifyAll();
    			
    //			if(count == 2) {
    //				System.out.println("线程B");
    //				count = 3;
    //				//Thread.currentThread().notifyAll();
    //				notifyAll();
    //			}else {
    //				//Thread.currentThread().wait(1000);
    //				wait();
    //			}
    		}
    	}
    	
    	public void c() throws InterruptedException {
    		synchronized (this) {
    			while(count != 3) {
    				wait();
    			}
    			System.out.println("线程C");
    			count = 1;
    			notifyAll();
    			
    //			if(count == 3) {
    //				System.out.println("线程C");
    //				count = 0;
    //				//Thread.currentThread().notifyAll();
    //				notifyAll();
    //			}else {
    //				//Thread.currentThread().wait(1000);
    //				wait();
    //			}
    		}
    	}
    	
    }
    
    public class ThreadA implements Runnable {
    	
    	private StepOver stepOver;
    	
    	public ThreadA(StepOver stepOver) {
    		this.stepOver = stepOver;
    	}
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		try {
    			stepOver.a();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    }
    
    public class ThreadB implements Runnable {
    	
    	private StepOver stepOver;
    	
    	public ThreadB(StepOver stepOver) {
    		this.stepOver = stepOver;
    	}
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		try {
    			stepOver.b();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    }
    
    public class ThreadC implements Runnable {
    	
    	private StepOver stepOver;
    	
    	public ThreadC(StepOver stepOver) {
    		this.stepOver = stepOver;
    	}
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		try {
    			stepOver.c();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    }
    
    /**
    	 * 方法三
    	 */
    	@Test
    	public void test3() {
    		StepOver stepOver = new StepOver();
    		for(int i=0; i<10 ; i++) {
    			Thread b = new Thread(new ThreadB(stepOver));
    			b.start();
    			Thread a = new Thread(new ThreadA(stepOver));
    			a.start();
    			Thread c = new Thread(new ThreadC(stepOver));
    			c.start();
    		}
    	}
    

      面试的时候,面试官问你怎么保证多个线程顺序执行多半都是考察多线程的join方法,join方法的实现调用了Object的wait方法,所以上面说到的方法1和方法3本质上是相通的。

  • 相关阅读:
    Android 面试知识集1
    Android 开发自己的网络收音机2——电台列表(SlidingMenu侧滑栏)
    Android 程序drawable资源保存到data目录
    Android 开发自己的网络收音机1——功能要求及设计方案
    Android内存机制分析2——分析APP内存使用情况
    Android内存机制分析1——了解Android堆和栈
    Android Gallery实现3D相册(附效果图+Demo源码)
    Android 后台发送邮件 (收集应用异常信息+Demo代码)
    纯代码写UI的时候,如何指定style?
    解决SimpleCursorAdapter不能自动更新的问题
  • 原文地址:https://www.cnblogs.com/mxh-java/p/11041570.html
Copyright © 2011-2022 走看看