线程的四种创建方式
转载线程的四种创建方式
线程交替打印
package test;
public class TurningRunner{
public static int count = 1;
public static Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
new Thread(new ChangePrintRunner(),"奇数").start();
Thread.sleep(1);
new Thread(new ChangePrintRunner(),"偶数").start();
}
}
class ChangePrintRunner implements Runnable{
@Override
public void run(){
while (TurningRunner.count<=100){
synchronized (TurningRunner.lock){
System.out.println(Thread.currentThread().getName()+" "+TurningRunner.count++);
TurningRunner.lock.notifyAll();
try{
if(TurningRunner.count<=100){
TurningRunner.lock.wait();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}