zoukankan      html  css  js  c++  java
  • JAVA单线程和多线程的实现方式

    1.java单线程的实现          一个任务一个人独立完成

    public class SingletonThread {
        @SuppressWarnings("static-access")
        public static void main(String[] args) {
             Thread t =Thread.currentThread();
             t.setName("单例线程");
         //有1000条数据需要更新,由一个人来完成
    for(int i=0;i<1000;i++){
          
    try {
              System.out.println(t.getName()+"正在执行"+i); //t.sleep(
    500); //线程休眠中 } catch (InterruptedException e) { System.out.println("线程出现错误了!!"); } } } }

    2.java多线程的实现                 一个任务多个人来同时进行并完成

    ①继承Thread类,并重写run方法

    public class ThreadImpl {
        public static void main(String[] args) {
         //这里也有1000条数据数据需要更新,就分3个人来进行完成 Thread t1
    =new ThreadTest("t1", 300); Thread t2=new ThreadTest("t2", 300); Thread t3=new ThreadTest("t3", 400); t1.start(); t2.start(); t3.start(); } } class ThreadTest extends Thread{ private String name; private int ts; public ThreadTest(String name, int ts) { this.name = name; this.ts= ts; } public void run() { try { //sleep(ms);
           for(int i=0;i<=ts;i++){
              System.out.println(name+"正在执行"+i);
           } }
    catch (InterruptedException e) { System.out.println("线程运行中断异常"); } System.out.println("名字叫"+name+"的线程开始休眠"+ms+"毫秒"); } }

    ②实现runnable接口,重写run方法

    public class RunnableImpl {
        public static void main(String[] args) {
            RunnableTest r1=new RunnableTest();
            Thread t=new Thread(r1);
             t.start();
        }
         
    }
     
    class RunnableTest implements Runnable{
         
        @Override
        public void run() {
            // TODO Auto-generated method stub
             
        }
         
    }

    这是一个线程模拟的售票系统:

    class MyThread implements Runnable{
        
        private int ticket=10;  //10张车票
        
        public void run(){  
            for(int i=0;i<=20;i++){  
                if(this.ticket>0){  
                    System.out.println(Thread.currentThread().getName()+"正在卖票:"+this.ticket--);  
                }  
            }  
        }
    }
    public class ThreadTicket{
    public static void main(String[] args) { //资源共享 MyThread mt=new MyThread(); new Thread(mt, "1号窗口").start(); new Thread(mt, "2号窗口").start(); new Thread(mt, "3号窗口").start(); } }

    【运行结果】:

    1号窗口正在卖票:9
    1号窗口正在卖票:7
    2号窗口正在卖票:6
    3号窗口正在卖票:5
    2号窗口正在卖票:4
    1号窗口正在卖票:3
    1号窗口正在卖票:2
    1号窗口正在卖票:1
    3号窗口正在卖票:8
    2号窗口正在卖票:10

  • 相关阅读:
    CodeForces 734F Anton and School
    CodeForces 733F Drivers Dissatisfaction
    CodeForces 733C Epidemic in Monstropolis
    ZOJ 3498 Javabeans
    ZOJ 3497 Mistwald
    ZOJ 3495 Lego Bricks
    CodeForces 732F Tourist Reform
    CodeForces 732E Sockets
    CodeForces 731E Funny Game
    CodeForces 731D 80-th Level Archeology
  • 原文地址:https://www.cnblogs.com/zhaojinhui/p/5315816.html
Copyright © 2011-2022 走看看