- <font size="3">public class TraditionalThreadItem {
- class Business{
- private boolean flag = true;
- public synchronized void sub(int i){
- if(!flag){
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- for(int j=1;j<=10;j++){
- System.out.println("sub thread squence of "+j+",loop of "+i);
- }
- flag = false;
- this.notifyAll();
- }
- public synchronized void main(int i){
- if(flag){
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- for(int j=1;j<=100;j++){
- System.out.println("main thread squence of "+j+",loop of "+i);
- }
- flag = true;
- this.notifyAll();
- }
- }
- public static void main(String[] args) {
- final Business business = new TraditionalThreadItem().new Business();
- new Thread(new Runnable(){
-
- @Override
- public void run(){
- for(int i=1;i<=50;i++){
- synchronized(TraditionalThreadItem.class){
- business.sub(i);
- }
- }
- }
- }).start();
-
- for(int i=1;i<=50;i++){
- synchronized(TraditionalThreadItem.class){
- business.main(i);
- }
- }
- }
- }</font>
复制代码 |
|