zoukankan      html  css  js  c++  java
  • 创建线程的两种方式,及线程同步

    1、创建线程的两种方式:

    (1)创建Thread类的子类,重写run方法

    class Thread1 extends Thread{       public void run(){ 重写方法体 }        }

    在main方法中:

    Thread1 t1 = new Thread1 (); 

     t1.start();

    (2)实现Runnable接口,重写run方法,再传入Thread类的实例参数中

    class Thread2 implements Runnable{  public void run(){   重写方法体}   }

    在main方法中:

    Thread2  t2 = new Thread2 ();

    Thread t = new Thread(t2);

    t.start();

    2、线程同步

    (1)同步方法:使调用该方法的线程均能获得对象的锁

    class Share{   synchronized void print(String str){ 方法体 }}

    被synchronized 的方法,一旦一个线程进入实例的同步方法中,直到当前线程执行完这个方法,其他线程才能进入。但该实例的非同步方法还是可以被其他线程调用的

    (2)同步块

    关联(1)中的类,class caller implements Runnable{

      string str;

      Share s;

      Thread t;

      public caller(Share s,String str){

        this.s = s;

        this.str = str;

        t = new Thread(this);

        t.start();

      }

      public void run (){

        synchronized(s){    //同步share对象

          s.print(str);

      }

      }

    }

  • 相关阅读:
    nodejs实战的github地址,喜欢的你还等啥
    java初始化深度剖析
    第三篇之消息的收发
    第二篇之收发消息的封装
    微信公众号开发第一篇之基本开发环境的搭建
    微信开发调试工具
    微信公众号开发入门教程第一篇
    linux常见驱动修改
    微信硬件开发步骤
    Linux系统快速启动方案
  • 原文地址:https://www.cnblogs.com/blackdd/p/8927287.html
Copyright © 2011-2022 走看看