俩个线程输出1-30,结果如下:
Thread-0 : 1
Thread-0 : 2
Thread-0 : 3
Thread-1 : 4
Thread-1 : 5
Thread-1 : 6
Thread-0 : 7
Thread-0 : 8
Thread-0 : 9
Thread-1 : 10
Thread-1 : 11
Thread-1 : 12
Thread-0 : 13
Thread-0 : 14
Thread-0 : 15
Thread-1 : 16
Thread-1 : 17
Thread-1 : 18
Thread-0 : 19
Thread-0 : 20
Thread-0 : 21
Thread-1 : 22
Thread-1 : 23
Thread-1 : 24
Thread-0 : 25
Thread-0 : 26
Thread-0 : 27
Thread-1 : 28
Thread-1 : 29
Thread-1 : 30
------解决方案--------------------
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);
}
}
}
}