解决方案 »

  1.   

    package TestProject;public class TestSynchronized { public static void main(String[] args) {
    TTSynchronized tt =  new TTSynchronized();
    Thread t1 = new Thread(tt);
    Thread t2 = new Thread(tt);
    t1.setName("Thread-1");
    t2.setName("Thread-0");
    t1.start();
    t2.start(); }}
    class TTSynchronized implements Runnable{
    static int i=0;
    public void run() {
    synchronized(this){
    for(i=0;i<30;i++){
    if(i%3==0){
    try {
    this.notify();
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println(Thread.currentThread().getName()+":"+i);
    }
    }
    }

    }
      

  2.   

    其实有很多种做法package com.test;public class Loader {
      final static Object lock = new Object();  static int counter = 0;  public static void main(String[] args) throws InterruptedException {    Runnable runnable = new Runnable() {
          @Override
          public void run() {
            while (true) {
              synchronized (lock) {
                int number = ++counter;
                if (number > 30)
                  return;
                System.out.println(Thread.currentThread().getName() + " " + number);
              }
              try {
                Thread.sleep(10);
              }
              catch (InterruptedException e) {
                e.printStackTrace();
              }
            }
          }
        };    Thread thread0 = new Thread(runnable, "Thread-0");
        Thread thread1 = new Thread(runnable, "Thread-1");    thread0.start();
        thread1.start();
      }
    }