多线程知识总结一 创建方式

1.创建方式

1. 声明Thread的子类,重写Thread类中的run()方法。通过调用线程.start()方法启动线程  

class ThreadDemo extends Thread

{

   public void run()

    {   

      synchronized(obj)

      {      

        }        //同步代码块

      }

}

class Mian

{

    public static void main(String [] args)

    {

        ThreadDemo x = new ThreadDemo()

          x.start();

    }

}

2. 声明Runnable接口,

a. 覆盖Runnable中的run()方法,

b. 通过Thread类建立线程对象,

c. 将Runnable接口的子类对象作为实际参数转递给Thread类的构造函数

d. 调用Thread类中的.start()方法开启线程

class threaddemo implements Runnable

{

   public void run()

    {   

      show();  

     }

      public synchronized void show()   //同步函数

      {

        xxxxx

      }

 

}

class Mian

{

    public static void main(String [] args)

    {

        ThreadDemo x = new ThreadDemo()

          Thread t = new Thread(x);

          //t.currentThread()   获取当前线程对象

          //t.setName("") 设置线程名称

            t.start();

    }

}

 

posted @ 2018-09-21 14:20  dber521  阅读(138)  评论(0)    收藏  举报