当前位置: 移动技术网 > IT编程>开发语言>Java > Java线程代码的实现方法

Java线程代码的实现方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

一、线程java代码实现

1.继承thread

声明thread的子类

public class mythread extends thread {
 public void run(){
  system.out.println("mythread running");
 }
}

运行thread子类的方法

mythread mythread = new mythread();
mytread.start();

2.创建thread的匿名子类

thread thread = new thread(){
 public void run(){
  system.out.println("thread running");
 }
};
thread.start();

3.实现runnable接口

声明

public class mythread implements runnable {
@override
public void run() {
 system.out.println("mythread is running");
}
}

运行

thread thread = new thread(new myrunnable());
thread.start();

4.创建实现runnable接口的匿名类

new thread(new runnable(){
 @override
 public void run() {
  system.out.println("thread is running");
 }
}).start();

5.线程名字

创建时候可以给线程起名字

thread thread = new thread(new myrunnable(),"name");?获得名字
thread thread = new thread(new myrunnable(),"name");
system.out.println(thraed.getname());?获取运行当期代码线程的名字
thread.currentthread().getname();

二、线程安全性

1.定义

线程会共享进程范围内的资源,同时,每个线程也会有各自的程序计数器,栈,以及局部变量。在多个线程不完全同步的情况下,多个线程执行的顺序是不可预测的,那么不同的执行顺序就可能带来极其糟糕的结果。


如何定义一个类是线程安全的呢?最核心的问题在于正确性,在代码中无需进行额外的同步或者协同操作的情况下,无论有多少个线程使用这个类,无论环境以何种方式调度多线程,这个类总能表现出正确的行为,我们就成这个类是线程安全的。

2.线程类不安全的实例

1.首先定义count类,有私有成员count=0;

public class count {
 private long count = 0;
 
 public long getcount() {
  return count;
 }
 
 public void service() {
  count++;
 }
}

2.然后在线程中去调用这个类的service方法

final count count = new count();
for (int i = 0; i < 20000; i++) {
 thread thread3 = new thread(){
  @override
  public void run() {
   count.service();
   if (count.getcount() == 20000) {
    system.out.println("ahha");
   }
  }
 };
 thread3.start();
}

3.结果程序却没有输出,说明最后count并没有达到20000,为什么呢?

因为存在着以下错误执行的情况:线程2在线程1没有完成count自增的情况下就读取了count,导致最后count没有达到20000。

4.并发编程中,这种由于不恰当的执行顺序而显示了不正确结果的情况叫做race condition(竞争状态),这种情况出现的根本原因是count的自增没有保持原子性。count自增分三步操作,而不是一步到位。

以上这篇java线程代码的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网