要求:子執行緒執行執行10次後,主線程再執行5次,這樣交替執行三遍
package multithread;
public class multithread
}}).start();
//主線程
for(int i=0;i<3;i++)
}//標識子程序是否可以執行
private static volatile boolean flag = true;
public synchronized void subthread()catch (interruptedexception e)
}//flag==true,子程序執行10次
for(int i=0;i<10;i++)
//喚醒主程序
flag=false;
notify();
}public synchronized void mainthread()catch (interruptedexception e)
}//flag==false時,主程序可以執行五次
for(int i=0;i<5;i++)
//喚醒子程序
flag=true;
notify();
}}
執行結果:
thread-0:sub method running 0
thread-0:sub method running 1
thread-0:sub method running 2
thread-0:sub method running 3
thread-0:sub method running 4
thread-0:sub method running 5
thread-0:sub method running 6
thread-0:sub method running 7
thread-0:sub method running 8
thread-0:sub method running 9
main:main method running 0
main:main method running 1
main:main method running 2
main:main method running 3
main:main method running 4
thread-0:sub method running 0
thread-0:sub method running 1
thread-0:sub method running 2
thread-0:sub method running 3
thread-0:sub method running 4
thread-0:sub method running 5
thread-0:sub method running 6
thread-0:sub method running 7
thread-0:sub method running 8
thread-0:sub method running 9
main:main method running 0
main:main method running 1
main:main method running 2
main:main method running 3
main:main method running 4
thread-0:sub method running 0
thread-0:sub method running 1
thread-0:sub method running 2
thread-0:sub method running 3
thread-0:sub method running 4
thread-0:sub method running 5
thread-0:sub method running 6
thread-0:sub method running 7
thread-0:sub method running 8
thread-0:sub method running 9
main:main method running 0
main:main method running 1
main:main method running 2
main:main method running 3
main:main method running 4
面試題 執行緒
今天公司新來的小夥伴問了我這樣乙個面試題 他不清楚為什麼最後輸出的是thread中的方法,而不是runnable中的方法,然後我看了下他從網上搜出的別人寫的答案,很多東西對於懂的人來說很容易就能看懂,但是對於剛剛踏入這一行業的人來說,他不明白。所以希望很多在這塊迷茫的小夥伴能夠更好的掌握這一點,那麼...
如何保證執行緒的執行順序(面試題)
public class threadtest static thread t2 new thread new runnable static thread t3 new thread new runnable 1 設定執行緒的執行優先順序 此方案不行 public static void main...
多執行緒面試題
題目 主線程執行10次,子執行緒執行10次,此過程重複50次 package com.thread.test function 主線程執行10次,子執行緒執行10次,此過程重複50次 public class threadproblem start for int j 0 j 50 j class ...