线程同步_synchronized
2021-01-04 22:29
标签:getname 线程 java turn runnable nts str extends star 线程同步_synchronized 标签:getname 线程 java turn runnable nts str extends star 原文地址:https://www.cnblogs.com/hapyygril/p/12983196.html//数据共享
package projict05;
import java.util.ArrayList;
public class test31{
public static void main(String[] args) {
TicketSaler t1=new TicketSaler("窗口一");
TicketSaler t2=new TicketSaler("窗口二");
t1.start();
t2.start();
}
}
class TicketSaler extends Thread{//只能单继承
private static TicketService ts=new TicketService();//静态
public TicketSaler(String name) {
super(name);
}
public synchronized static void saleOneTicket() {//静态
if(ts.hasTicket()) {//用于安全检查
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ts.sale());
}
}
public void run() {
while(ts.hasTicket()) {
saleOneTicket();
}
}
}
class TicketService {
private ArrayListpackage projict06;
import java.util.ArrayList;
public class test32 {
public static void main(String[] args) {
MyRun my=new MyRun();
Thread t1=new Thread(my,"窗口一");
Thread t2=new Thread(my,"窗口二");
t1.start();
t2.start();
}
}
class MyRun implements Runnable{//可实现多接口
private TicketService ts=new TicketService();//非静态
public synchronized void saleOneTicket() {//非静态
if(ts.hasTicket()) {//用于安全检查
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ts.sale());
}
}
public void run() {
while(ts.hasTicket()) {
saleOneTicket();
}
}
}
class TicketService {
private ArrayList
上一篇:Leetcode练习(python):第414题:第三大的数:给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
下一篇:Go语言系列之日志库zap