package method;
public class Demo {
public static void main(String[] args) {
MyRunable mr = new MyRunable();
Thread tr1 = new Thread(mr);
Thread tr2 = new Thread(mr);
tr1.setName("张三");
tr2.setName("李四");
tr1.start();
tr2.start();
}
}
package method;
public class MyRunable implements Runnable {
private int tickecount = 100;
@Override
public void run() {
while (true) {
// 同步方法
// 如果获取线程的名字是张三那么就走同步方法
if ("张三".equals(Thread.currentThread().getName())){
boolean reasult = method();
if(reasult){
break;
}
}
// 同步代码块
// 如果获取的线程名字是李四,那么就走同步代码块
if ("李四".equals(Thread.currentThread().getName())){
synchronized (this){
if (tickecount == 0) {
break;
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickecount--;
System.out.println(Thread.currentThread().getName() + "还在卖票,还剩" + tickecount + "张");
}
}
}
}
}
//可以先run方法中写好,通过快捷键提取方法
// 同步方法主要就是在返回值前加synchronized,返回值是一个boolean类型的值
private synchronized boolean method() {
if (tickecount == 0) {
return true;
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickecount--;
System.out.println(Thread.currentThread().getName() + "还在卖票,还剩" + tickecount + "张");
}
return false;
}
}