java多线程

来源:互联网 发布:小超市供销存管理优化 编辑:程序博客网 时间:2024/06/04 18:22

单线程程序

每个程序至少有一个线程,程序执行一开始就会有一个默认的线程,这个即就是主线程。单线程程序就是只有默认主线程的程序,在java程序中通常为main函数。

public class MainDemo {public static void main(String args[]){for (int x = 0; x < 60; x++) {System.out.println(Thread.currentThread().getName()+x);}}}

多线程程序

多线程编程实现的方法有两种:

一、继承Thread类,重写该类的run方法

class Demo extends Thread{public void run() {for (int x = 0; x < 60; x++) {System.out.println(Thread.currentThread().getName()+x);}}}public class DemoThread {public static void main(String args[]) {Demo demo = new Demo();demo.start();for (int x = 0; x < 60; x++) {System.out.println(Thread.currentThread().getName()+x);}}}

二、实现Runnable接口,重写run方法

class Demo implements Runnable {public void run() {for (int x = 0; x < 60; x++) {System.out.println(Thread.currentThread().getName()+x);}}}public class DemoThread {public static void main(String args[]) {Demo demo = new Demo();Thread t = new Thread(demo);t.start();for (int x = 0; x < 60; x++) {System.out.println(Thread.currentThread().getName()+x);}}}

线程同步

火车购票通常会面临一个问题,当多人同时购票的时候,购票程序就会对同一资源进行操作,如果还剩下一张票,有一个人看到,然后购票成功,同时另外一个人也是看到火车票还剩下一张,两个人同时进行购票,如果购票成功显然会出错。

以上的问题就是多线程安全,当多个线程各自操作不同的资源的时候,程序不会出错。当多个线程操作同一个资源的时候,就要面临着资源分配的问题。

以下就是解决线程同步的方法(购票程序):

//购票服务public class Service {private String ticketName;private int ticketSum;private int remain;public Service(String ticketName, int ticketSum) {this.ticketName = ticketName;this.ticketSum = ticketSum;this.remain = ticketSum;}public synchronized int SaleTicket(int ticket){if(remain > 0){remain -= ticket;try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (remain >= 0) {return remain;}else{remain += ticket;return -1;}}return -1;}public synchronized int getremain() {return remain;}public String getTicketName() {return ticketName;}}

//多线程public class TicketSaler implements Runnable {private String name;private Service service;public TicketSaler (String name, Service service){this.name = name;this.service = service;}public void run() {while(service.getremain() > 0) {synchronized(this) {System.out.println(Thread.currentThread().getName() + "出售第" +service.getremain() + "张票");int remain = service.SaleTicket(1);if (remain >= 0) {System.out.println("出售成功!剩余" + remain +"张票");}else{System.out.println("出票失败!该票已售完");}}}}}
</pre><p><pre name="code" class="java">//主程序public class SaleSystem {public static void main(String args[]){Service service = new Service ("北京-->上海",5);TicketSaler sale = new TicketSaler("售票程序", service);Thread thread[] = new Thread[8];for (int i = 0; i < thread.length; i++) {thread[i] = new Thread(sale, "窗口"+(i + 1));thread[i].start();}}}

0 0
原创粉丝点击