zoukankan      html  css  js  c++  java
  • 多线程

    多个线程同时操作一个共享资源时,仍然能得到正确结果。就是线程安全。

    Java语言内置了多线程支持。当Java程序启动的时候,实际上是启动了一个JVM进程,然后,JVM启动主线程来执行main()方法。在main()方法中,我们又可以启动其他线程。

    1.

    public class Main {
    public static void main(String[] args) {
    Thread t = new Thread();
    t.start(); // 启动新线程
    }
    }

    2.使用线程:

    public class Main {
    public static void main(String[] args) {
    Thread t = new MyThread();
    t.start(); // 启动新线程
    }
    }

    class MyThread extends Thread {
    @Override
    public void run() {
    System.out.println("start new thread!");
    }
    }

    3.创建Thread实例时,传入一个Runnable实例:

    public class Main {
    public static void main(String[] args) {
    Thread t = new Thread(new MyRunnable());
    t.start(); // 启动新线程
    }
    }

    class MyRunnable implements Runnable {
    @Override
    public void run() {
    System.out.println("start new thread!");
    }
    }

    4.或者用Java8引入的lambda语法进一步简写为:

    public class Main {
    public static void main(String[] args) {
    Thread t = new Thread(() -> {
    System.out.println("start new thread!");
    });
    t.start(); // 启动新线程
    }
    }

    5.

  • 相关阅读:
    第七周总结
    结对开发nabcd
    第六周总结
    地铁售票设计思想及部分代码
    第二周总结
    进度总结(地铁查询购票)
    第三周总结
    冲刺四
    冲刺三
    冲刺2
  • 原文地址:https://www.cnblogs.com/levin180425/p/13074335.html
Copyright © 2011-2022 走看看