2020.02.14 同步锁

package com.guoyun.ThreadTest;

/**
* ClassName:
* Function: ADD FUNCTION
* Reason: ADD REASON
*
* @author
* @Date
* @since Ver 1.1
*/
public class Test3 {
public static void main(String[] args){
PrintMethod pm=new PrintMethod();
Thread t1=new Thread(pm);
Thread t2=new Thread(pm);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
class PrintMethod implements Runnable{
private int i=1;
@Override
public void run() {
while (true)
synchronized (this) {
if (i<=100){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在打印" + i);
i++;
}else {
break;
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/aojie/p/12306673.html