Java多线程源码

单线程程序

public static void main(String args[]) {
   System.out.println("输出从1到100的数:");
   for (int i = 0; i < 100; i ++) {
      System.out.println(i + 1);
   }
}

线程的创建和使用

class ThreadA implements Runnable {
   private Thread thread;
   private String threadName;
   public ThreadA(String threadName) {
      thread = new Thread(this, threadName);
      this.threadName = threadName;
   }

   //实现run方法
   public void run() {
      for (int i = 0; i < 100; i ++) {
         System.out.println(threadName + ": " + i);
      }
   }

   public void start() {
      thread.start();
   }
}

/**
 * 继承Thread的方法
 */
class ThreadB extends Thread {
   private String threadName;

   public ThreadB(String threadName) {
      super(threadName);
      this.threadName = threadName;
   }

   //实现run方法
   public void run() {
      for (int i = 0; i < 100; i ++) {
         System.out.println(threadName + ": " + i);
      }
   }
}

public class MultiThread{

   public static void main(String args[]) {
      ThreadA threadA = new ThreadA("ThreadA");
      ThreadB threadB = new ThreadB("ThreadB");
      threadA.start();
      threadB.start();
   }
}

火车票售票系统模拟程序

/**
 * 模拟服务器的类
 */
class Service {
   private String ticketName;    //票名
   private int totalCount;        //总票数
   private int remaining;        //剩余票数

   public Service(String ticketName, int totalCount) {
      this.ticketName = ticketName;
      this.totalCount = totalCount;
      this.remaining = totalCount;
   }

   public synchronized int saleTicket(int ticketNum) {
      if (remaining > 0) {
         remaining -= ticketNum;
         try {        //暂停0.1秒,模拟真实系统中复杂计算所用的时间
            Thread.sleep(100);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }

         if (remaining >= 0) {
            return remaining;
         } else {
            remaining += ticketNum;
            return -1;
         }
      }
      return -1;
   }

   public synchronized int getRemaining() {
      return remaining;
   }

   public String getTicketName() {
      return this.ticketName;
   }

}

/**
 * 售票程序
 */
class TicketSaler implements Runnable {
   private String name;
   private Service service;

   public TicketSaler(String windowName, Service service) {
      this.name = windowName;
      this.service = service;
   }

   @Override
   public void run() {
      while (service.getRemaining() > 0) {
         synchronized (this)
         {
            System.out.print(Thread.currentThread().getName() + "出售第" + service.getRemaining() + "张票,");
            int remaining = service.saleTicket(1);
            if (remaining >= 0) {
               System.out.println("出票成功!剩余" + remaining + "张票.");
            } else {
               System.out.println("出票失败!该票已售完。");
            }
         }
      }
   }
}
/**
 * 测试类
 */
public class TicketingSystem {
   public static void main(String args[]) {
      Service service = new Service("北京-->赣州", 500);
      TicketSaler ticketSaler = new TicketSaler("售票程序", service);
      //创建8个线程,以模拟8个窗口
      Thread threads[] = new Thread[8];
      for (int i = 0; i < threads.length; i++) {
         threads[i] = new Thread(ticketSaler, "窗口" + (i + 1));
         System.out.println("窗口" + (i + 1) + "开始出售 " + service.getTicketName() + " 的票...");
         threads[i].start();
      }

   }
}

线程中断的应用

/**
 * 打印线程
 */
class Printer implements Runnable {
   public void run() {
      while (!Thread.currentThread().isInterrupted()) {     //如果当前线程未被中断,则执行打印工作
         System.out.println(Thread.currentThread().getName() + "打印中… …");
      }
      if (Thread.currentThread().isInterrupted()) {
         System.out.println("interrupted:" +  Thread.interrupted());       //返回当前线程的状态,并清除状态
         System.out.println("isInterrupted:" +  Thread.currentThread().isInterrupted());
      }
   }

   public static void main(String args[]){
       Printer printer = new Printer();
       Thread printerThread = new Thread(printer, "打印线程");
       printerThread.start();
       try {
           Thread.sleep(100);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       System.out.println("有紧急任务出现,需中断打印线程.");
       System.out.println("中断前的状态:" + printerThread.isInterrupted());
       printerThread.interrupt();       // 中断打印线程
       System.out.println("中断前的状态:" + printerThread.isInterrupted());
   }
}

线程合并

/**
 * 插件1
 */
class Plugin1 implements Runnable {

   @Override
   public void run() {
      System.out.println("插件1开始安装.");
      System.out.println("安装中...");
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      System.out.println("插件1完成安装.");
   }
}

/**
 * 插件2
 */
class Plugin2 implements Runnable {

   @Override
   public void run() {
      System.out.println("插件2开始安装.");
      System.out.println("安装中...");
      try {
         Thread.sleep(2000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      System.out.println("插件2完成安装.");
   }
}

合并线程调用

System.out.println("主线程开启...");
Thread thread1 = new Thread(new Plugin1());
Thread thread2 = new Thread(new Plugin2());
try {
   thread1.start();   //开始插件1的安装
   thread1.join();       //等插件1的安装线程结束
   thread2.start();   //再开始插件2的安装
   thread2.join();       //等插件2的安装线程结束,才能回到主线程
} catch (InterruptedException e) {
   e.printStackTrace();
}
System.out.println("主线程结束,程序安装完成!");

线程优先级

/**
 * 优先级
 */
class PriorityThread implements Runnable{
   @Override
   public void run() {
      for (int i = 0; i < 1000; i ++) {
         System.out.println(Thread.currentThread().getName() + ": " + i);
      }
   }
}

调用代码:

//创建三个线程
Thread thread1 = new Thread(new PriorityThread(), "Thread1");
Thread thread2 = new Thread(new PriorityThread(), "Thread2");
Thread thread3 = new Thread(new PriorityThread(), "Thread3");
//设置优先级
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(8);
//开始执行线程
thread3.start();
thread2.start();
thread1.start();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值