服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java实现Runnable接口适合资源的共享

java实现Runnable接口适合资源的共享

2021-05-17 15:30xusheng_Mr Java教程

这篇文章主要为大家详细介绍了java实现Runnable接口适合资源的共享,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文为大家分享了java实现runnable接口适合资源的共享,供大家参考,具体内容如下

java当中,创建线程通常用两种方式:

1、继承thread类

2、实现runnable接口

但是在通常的开发当中,一般会选择实现runnable接口,原因有二:
1.避免单继承的局限,在java当中一个类可以实现多个接口,但只能继承一个类
2.适合资源的共享
原因1我们经常听到,但是2是什么呢?下面用一个例子来解释:
有5张票,分两个窗口卖:

继承thread类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class threaddemo {
  public static void main(string[] args) {
    hellothread t1 = new hellothread();
    t1.setname("一号窗口");
    t1.start();
    hellothread t2 = new hellothread();
    t2.setname("二号窗口");
    t2.start();
  }
 
}
class hellothread extends thread{
 
   private int ticket = 5;
  public void run() {
    while(true){
      system.out.println(this.getname()+(ticket--));
      if (ticket<1) {
        break
      }
    }
  }
 
}

运行结果:

java实现Runnable接口适合资源的共享

很明显,这样达不到我们想要的结果,这样两个窗口在同时卖票,互不干涉。

实现thread类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class threaddemo {
  public static void main(string[] args) {
    hellothread t = new hellothread();
    thread thread1 = new thread(t, "1号窗口");
    thread1.start();
    thread thread2 = new thread(t, "2号窗口");
    thread2.start();
  }
 
}
class hellothread implements runnable{
 
  private int ticket = 5;
  public void run() {
    while(true){
      system.out.println(thread.currentthread().getname()+(ticket--));
      if (ticket<1) {
        break
      }
    }
  }
 
}

运行结果:

java实现Runnable接口适合资源的共享

这样两个窗口就共享了5张票,因为只产生了一个hellothread对象,一个对象里边有一个属性,这样两个线程同时在操作一个属性,运行同一个run方法。

这样就达到了资源的共享。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xusheng_Mr/article/details/61938216

延伸 · 阅读

精彩推荐