当前位置: 移动技术网 > IT编程>脚本编程>Erlang > java线程锁基础

java线程锁基础

2019年08月06日  | 移动技术网IT编程  | 我要评论
定义运行方法

package com.company; // 包名
import java.util.concurrent.locks.reentrantlock;
import java.util.concurrent.locks.lock;
public class ticket implements runnable{
private int ticketnum = 100; //全局变量
lock lock = new reentrantlock(true); //对象
@override
public void run() { //写 run()
while (ticketnum > 0){
lock.lock(); //加锁
try {
if (ticketnum > 0){
try {
thread.sleep(100); //工作时间
} catch (interruptedexception e) {
e.printstacktrace();
}
string name = new thread().currentthread().getname();
system.out.println("线程"+name+"销售电影票"+ticketnum--);
}
}
finally {
lock.unlock(); //解锁
}
}
}
}


将方法加入到线程中
package com.company;
import com.company.ticket;
public class shoupiao {
public static void main(string[] args) {
ticket ticket = new ticket();
thread thread1 = new thread(ticket,"窗口1");
thread thread2 = new thread(ticket,"窗口2");
thread thread3 = new thread(ticket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}






如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网