宇筱博客

  • 解决办法
  • 学无止境
  • 记录时光
  • 百宝箱
宇筱博客
点滴记忆,汇聚成海。
  1. 首页
  2. 解决办法
  3. 正文

Java实现多线程的几种方法

2019年1月3日 398点热度 0人点赞 0条评论

1,多线程有两种实现方法。

一种是继承Thread类,一种是实现Runnable接口!

1.1,一种是继承Thread类

public class classA() extends Thread {            // 继承Thread类

 public void run () {                            // 覆盖run()方法

   system.out.println("multi-thread");

 }

 pubic static void main(String args[]) {

   classA clsA = new classA();

   clsA.start();                                 // 启动线程

 }

}

1.2,一种是实现Runnable接口

public class classB() implements Runable {         // 实现Runnable接口

 public void run() {                             // 覆盖run()方法

  system.out.println("multi-thread");

 }

 public void main (string args[]) {

   classB clsB = new classB();

   Thread t1 = new Thread(clsB);

   t1.start();                                 // 启动线程

 }

}

2,同步有两种实现方法。

一种同步方法,一种同步代码!分别是synchronized,wait与notify

2.1.一种是用同步代码块

 同步代码块就是直接写:synchronized (这里写需要同步的对象){...}

public void main(string args[]){

 private Well well;

 public class Well() {

   system.out.println("Well");

 }

 sychronized(well){                             // 同步代码块

   String a = "";

   system.out.println(a);

 }

 public viod methodB(){

  system.out.println("methodB");

 }

}

2.2.一种是用同步方法

同步方法就是在方法返回类型后面加上synchronized,表示一个方法中的所有代码都是同步代码

public void synchronized add(){                // 同步方法

 sleep(100);

 sytem.out.println("sleep");

}

标签: 暂无
最后更新:2019年1月3日

小渔民

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2025 宇筱博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备15017825号-2