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);

      }

      }

    }

  • 相关阅读:
    Max Sum Plus Plus HDU
    Monkey and Banana HDU
    Ignatius and the Princess IV HDU
    Extended Traffic LightOJ
    Tram POJ
    Common Subsequence HDU
    最大连续子序列 HDU
    Max Sum HDU
    畅通工程再续
    River Hopscotch POJ
  • 原文地址:https://www.cnblogs.com/blackdd/p/8927287.html
Copyright © 2011-2022 走看看