//多线程之同步(方法)重点:synchronized关键字
class Ticket1 implements Runnable {
private int tickets = 10;
@Override
public void run() {
while (true) {
saleTicket();
if (tickets <= 0) {
break;
}
}
}
private synchronized void saleTicket() {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Ticket1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(Thread.currentThread().getName() + "---卖出的票" + tickets--);
}
}
}
public class Test3 {
public static void main(String[] args) {
Ticket1 ticket = new Ticket1();
new Thread(ticket, "线程一").start();
new Thread(ticket, "线程二").start();
new Thread(ticket, "线程三").start();
new Thread(ticket, "线程四").start();
}
}
//多线程之同步(代码块)
class Ticket implements Runnable {
private int tickets = 1000;
Object lock = new Object();
public void run() {
while (true) {
synchronized (lock) {
try {
Thread.sleep(10);//经过的线程休眠10毫秒
} catch (InterruptedException ex) {
Logger.getLogger(Ticket.class.getName()).log(Level.SEVERE, null, ex);
}
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "--卖出的票" + tickets--);
} else {
break;
}
}
}
}
}
public class Test2 {
public static void main(String[] args) {
Ticket ticket=new Ticket();
new Thread(ticket,"线程一").start();
new Thread(ticket,"线程二").start();
new Thread(ticket,"线程三").start();
new Thread(ticket,"线程四").start();
}
}
//多线程之插队 重点:.join()方法
class Thread1 implements Runnable {
@Override
public void run() {
for (int i = 1; i < 6; i++) {
System.out.println(Thread.currentThread().getName() + "输入:" + i);
try {
Thread.sleep(500);//线程休眠500毫秒
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class Test4 {
public static void main(String[] args) throws Exception {
Thread t = new Thread(new Thread1(), "线程一");
t.start();
for (int i = 1; i < 6; i++) {
System.out.println(Thread.currentThread().getName() + "输入:" + i);
if (i == 2) {
t.join();
}
Thread.sleep(500);
}
}
}
Java多线程集锦
最新推荐文章于 2021-08-31 19:47:59 发布
本文深入探讨了Java多线程编程的各个方面,包括线程创建、同步机制、死锁避免、线程池的使用以及Java并发工具类的应用。通过实例解析,帮助读者掌握高效且安全的多线程编程技巧。
摘要由CSDN通过智能技术生成