线程面试题
1.在使用線程時,為什么不直接調用run()方法而是調用了start():
直接調用run()方法,不存在線程的啟動,屬于調用實例方法,只有一條執行路徑,不存在多線程并行交替執行了。調用start()方法屬于啟動線程,將自動調用run()方法
2.子線程循環 10次,接著主線程循環 100次,接著又回到子線程循環 10次,接著再回到主線程又循環 100次,如此循環50次
public class ThreadTest{ public static void main(String[] args) { final MyThread threads=new MyThread(); new Thread( new Runnable(){ public void run(){ for(int i=1;i<=50;i++){ threads.subThread(i); } } } ).start(); new Thread(new Runnable(){ public void run(){ for(int i=1;i<=50;i++){ threads.mainThread(i); } } }).start(); } } class MyThread{ boolean bShouldSub=true;//標志子線程方法是否被調用 public synchronized void subThread(int i){ if(!bShouldSub){//若子線程沒被調用,即主線程正在運行,所以等待 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j=1;j<=10;j++){ System.out.println("sub thread :"+i+",loop : "+j); } bShouldSub=false;//子線程運行完畢 this.notify();//喚醒其他線程,即主線程 } public synchronized void mainThread(int i){ if(bShouldSub){//若子線程正在被調用,所以等待 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j=1;j<=100;j++){ System.out.println("main thread :"+i+",loop : "+j); } bShouldSub=true;//主線程調用完畢 this.notify();//喚醒子線程 } }3.編寫一個程序,開啟3個線程,這3個線程的ID分別為A、B、C,每個線程將自己的ID在屏幕上打印10遍,要求輸出結果必須按ABC的順序顯示
public class TestThread { /** * @author lucky */ public static void main(String[] args) { new Thread(new TestRun("A")).start(); new Thread(new TestRun("B")).start(); new Thread(new TestRun("C")).start(); } } class TestRun implements Runnable { private String name; private static String flag = "A"; private int count = 10; TestRun(String name) { this.name = name; } @Override public void run() { while (count > 0) { synchronized (flag) { if (flag.equals(name)) { System.out.print(name); count--; if (name.equals("A")) flag = "B"; if (name.equals("B")) flag = "C"; if (name.equals("C")) flag = "A"; } } } } }4.wait()方法和sleep()方法的區別:
1.wait()方法用于將當前線程處于等待狀態,它是Object類的;sleep()是將當前線程休眠,它是Thread
2.wait()將鎖釋放,sleep()方法不會釋放鎖
5.生產者和消費者
轉載于:https://www.cnblogs.com/xiao-ran/p/10735496.html
總結
- 上一篇: C#相对路径
- 下一篇: leetcode 994.腐烂的橘子