欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java线程锁基础

程序员文章站 2022-03-02 09:13:17
定义运行方法package com.company; // 包名import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.locks.Lock;public class ticket implements ......
定义运行方法

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();
}
}