经典进程问题:5个窗口卖100张票,卖完为止。用Runnable和Thread2种方法实现

简介: 经典进程问题:5个窗口卖100张票,卖完为止。用Runnable和Thread2种方法实现

Thread实现方式

  1. TicketThread类代码如下:
import java.util.Random;
public class TicketThread  extends Thread{
  private static   int i=1;
  Thread th =Thread.currentThread();
  String name;
  public TicketThread(String name) {
    super();
    this.name = name;
  }
  public  void run() {
 while(i<=96) {
           try {
      th.sleep(new Random().nextInt(1000));
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }     
           synchronized(this) {
             System.out.println(this.name+",出售第"+i+"张票");
            i++;
           }
 }       
  }
}
  1. TestThread类代码如下(TicketThread)的实现类
public class TestThread {
  public static void main(String[] args) {
    TicketThread th1 = new TicketThread("窗口1");
    TicketThread th2 = new TicketThread("窗口2");
    TicketThread th3 = new TicketThread("窗口3");
    TicketThread th4 = new TicketThread("窗口4");
    TicketThread th5 = new TicketThread("窗口5");
    th1.start();
    th2.start();
    th3.start();
    th4.start();
    th5.start();
  }
}

Runnable实现方式

  1. TicketRunnable类代码如下:
public class TicketRunnable implements Runnable {
  Thread th = Thread.currentThread();
  int i = 1;
  public void run() {
    while (i <= 96) {
      try {
        th.sleep(50);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      synchronized (this) {
        System.out.println(Thread.currentThread().getName() + ",出售第" + i + "张票");
        i++;
      }
    }
  }
}
  1. TestRunnable类代码如下(TicketRunnable的实现类)
public class TestRunnable {
  public static void main(String[] args) {
    TicketRunnable  tr =new TicketRunnable();
    Thread th1 = new Thread(tr,"窗口1");
    Thread th2 = new Thread(tr,"窗口2");
    Thread th3 = new Thread(tr,"窗口3");
    Thread th4 = new Thread(tr,"窗口4");
    Thread th5 = new Thread(tr,"窗口5");
    th1.start();
    th2.start();
    th3.start();
    th4.start();
    th5.start();
  }
}
目录
相关文章
|
2月前
|
安全 Linux 开发者
⭐⭐⭐⭐⭐Linux C/C++ 进程崩溃诊断以及有效数据收集:解锁代码问题快速定位与修复的方法
⭐⭐⭐⭐⭐Linux C/C++ 进程崩溃诊断以及有效数据收集:解锁代码问题快速定位与修复的方法
85 1
|
12天前
|
Python
多ip多进程代理的实现方法
多ip多进程代理的实现方法
|
4月前
|
Python
Python Appium Selenium 查杀进程的实用方法
Python Appium Selenium 查杀进程的实用方法
37 1
|
5月前
|
Linux
百度搜索:蓝易云【Linux系统下获取系统、BIOS、进程、网络等相关信息的方法和工具。】
综上所述,通过使用命令行工具和图形化工具,可以在Linux系统下获取系统、BIOS、进程和网络等相关信息。根据具体的需求和使用场景,选择合适的工具和命令可以帮助你更好地了解和管理Linux系统。
65 2
|
6月前
|
网络协议 安全 Unix
6种查看Linux进程占用端口号的方法
6种查看Linux进程占用端口号的方法
410 0
|
8月前
|
前端开发 API
Electron 渲染进程之间互相通信 创建窗口时触发
Electron 渲染进程之间互相通信 创建窗口时触发
|
8月前
|
Linux Apache
百度搜索:蓝易云【Linux查看进程PID的方法?】
在Linux系统中,进程是指正在运行的程序。每个进程都有一个唯一的进程 ID(PID),可以用来识别和管理它们。
207 0
|
9月前
python-- 进程的 join 方法和 is_alive 方法
python-- 进程的 join 方法和 is_alive 方法
|
9月前
|
运维 网络协议 Linux
Linux系统之查看进程监听端口方法
Linux系统之查看进程监听端口方法
257 0
|
12月前
|
Linux Shell 网络安全
Linux 让进程在后台可靠运行的几种方法
Linux 让进程在后台可靠运行的几种方法
104 0