About Java multi-threaded Runnable personal understanding (based on the concept do not speak)

Background note:

In the study of multi-threaded Java (inherited Thread, Runnable) later, out of curiosity, I wanted to know java in the end is not multi-threaded, it can not be said that he is multi-threaded multi-threaded, they want to test, so I wanted to test, but inherited thread due to a single form of inheritance java, leading to not generate multi-threaded, but Runnable can, so I made a script (personal feeling a java file is a script that did not rise to the project level), I also generate 10 threads, to simulate the ticketing system, assuming a thread to simulate a person to buy 10 tickets, a person buys a ticket time is 0.5s (not simultaneously to purchase two tickets and more), then observed that 100 how much time to complete the ticket purchase.

Problems encountered 1:

Problem Description:

First is to calculate a share how much time, and I made use of the code framework as shown below to write, found a problem: because the current java main program is a thread, when the main java program at runtime, after you have created these 10 threads, the main Java program execution is complete, it will not control whether this 10 threads run is complete, when the time is calculated, there is a problem. The total time will be output (output Time is not running threads) running thread

Solving Step 1:

The solution figure, explain: I define a thread static shared variables in the interface implementation class, this time, when the 10 threads to create and run a successful, when the last thread running is endTIme were last modified, the endTime the ten thread is running to complete the final time, then time is calculated. Problems will come, still does not solve the statistical time since java is still a main thread, time of the output error.

Solve Step 2:

Taking into account the main program is a java thread, I created 10 threads, Sleep Now java main thread (Estimated time in advance and set the sleep time), estimated sleep time is slightly larger than the threaded computing time

At last:

Time to solve the problem, but this time led to a big problem when 10 threads when accessing the same data and modify, the data may be at fault. This time we need to thread mutual exclusion mechanism for data.

Code:

The main program java code: javaThreadTest

package org.axc.com.javathread;

import java.util.Scanner;

/**
 * 
    * @ClassName: javaThreadTest
    * @Description: 测试java线程的运行
    * @author Anxc
    * @date 2019年8月8日
    *
 */
public class JavaThreadTest {
    public static void main(String[] args) {
//      线程的创建
        MyThread mythread;
        
        System.out.println("---------继承Thread方式来实现创建线程-----------------");
        Scanner in = new Scanner(System.in);
        String menu="线程测试开始";
        int chioce=1;
        
        while(chioce!=0) {
            
            mythread = new MyThread();
            System.out.println("请输入非0来开始调试继承的Thread");
            System.out.print(">>");
            chioce = in.nextInt();
            if(chioce==0) {
                System.out.println("ByeBye");
                break;
            }
//          输出菜单
            System.out.println(menu);
            
//          线程运行
            mythread.start();
        }
        
        System.out.println("------------利用Runnable接口实现创建线程-------------");
//      测试Runnable的多线程所用时间
        chioce = 1;
//      利用Runnable接口,初始化线程
        Runnable runnable = new MyRunnable();
        long startTime;
        long endTime;
        
        while(chioce!=0) {
            System.out.println("请输入非0来开始调试");
            System.out.print(">>");
            chioce = in.nextInt();
            if(chioce == 0) {
                System.out.println("Runnable ByeBye!");
                break;
            }
            startTime = System.currentTimeMillis();
            System.out.println(startTime);
//          创建10个线程来观察是否是真的多线程运行
            new Thread(runnable).start();
              new Thread(runnable).start();
              new Thread(runnable).start(); 
              new Thread(runnable).start(); 
              new Thread(runnable).start(); 
              new Thread(runnable).start(); 
              new Thread(runnable).start(); 
              new Thread(runnable).start(); 
              new Thread(runnable).start(); 
              new Thread(runnable).start();
              
              Thread t=new Thread(runnable);
              //t.isAlive();//判断线程是否存活
             try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
//          输出最后所用时间
            System.out.println("最终所用时间为:"+(((MyRunnable) runnable).getEndTime()-startTime));
        }
    }

}

java program code that implements the interface Runnable of: MyRunnable

package org.axc.com.javathread;

/**
 * 
    * @ClassName: MyRunnable
    * @Description: 测试Runnable的真正多线程
    * @author Anxc
    * @date 2019年8月8日
    *
 */
public class MyRunnable implements Runnable {
    private static int count=100;    //加互斥锁,当一个线程去修改值时,其它线程不能读取
    public static long endTime;
    private static boolean flag=true;
    
    public MyRunnable() {
        
    }

    @Override
    public void run() {
        
        int num=10;
//      加锁,使修改变量时只有一个线程在操作
        while(num>0) {
            if(flag) {
                flag=false;//加锁
            count--;
            // TODO Auto-generated method stub
            System.out.println("当前剩余"+count);
            flag=true;//关锁
            }
            else {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                continue;
                
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            num--;
        }
        
//      获取线程运行终止时间
        endTime = System.currentTimeMillis();
//      System.out.println(endTime);
    }
    
    public long getEndTime() {
        return endTime;
        
    }

}

继承Thread的方法的java程序:MyThread

package org.axc.com.javathread;

/**
 * 
    * @ClassName: MyThread
    * @Description: java线程的实现方式之一继承Thread
    * @author Anxc
    * @date 2019年8月8日
    *
 */
public class MyThread extends Thread {
    private static int count = 0;
    public void run() {
        
        int num=0;
        count++;
        while(num<5) {
            System.out.println("再等等!"+count+num);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            num++;
        }
        System.out.println("当前已经累计运行该线程:"+count+"次");
    }

}

Guess you like

Origin www.cnblogs.com/Anxc/p/11329051.html