在Java 中多线程的实现方法有哪些,如何使用

Python016

在Java 中多线程的实现方法有哪些,如何使用,第1张

Java多线程的创建及启动

Java中线程的创建常见有如三种基本形式

1.继承Thread类,重写该类的run()方法

复制代码

1 class MyThread extends Thread {

2  

3     private int i = 0

4

5     @Override

6     public void run() {

7         for (i = 0i <100i++) {

8             System.out.println(Thread.currentThread().getName() + " " + i)

9         }

10     }

11 }

复制代码

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4         for (int i = 0i <100i++) {

5             System.out.println(Thread.currentThread().getName() + " " + i)

6             if (i == 30) {

7                 Thread myThread1 = new MyThread()    // 创建一个新的线程  myThread1  此线程进入新建状态

8                 Thread myThread2 = new MyThread()    // 创建一个新的线程 myThread2 此线程进入新建状态

9                 myThread1.start()                    // 调用start()方法使得线程进入就绪状态

10                 myThread2.start()                    // 调用start()方法使得线程进入就绪状态

11             }

12         }

13     }

14 }

复制代码

如上所示,继承Thread类,通过重写run()方法定义了一个新的线程类MyThread,其中run()方法的方法体代表了线程需要完成的任务,称之为线程执行体。当创建此线程类对象时一个新的线程得以创建,并进入到线程新建状态。通过调用线程对象引用的start()方法,使得该线程进入到就绪状态,此时此线程并不一定会马上得以执行,这取决于CPU调度时机。

2.实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。

复制代码

1 class MyRunnable implements Runnable {

2     private int i = 0

3

4     @Override

5     public void run() {

6         for (i = 0i <100i++) {

7             System.out.println(Thread.currentThread().getName() + " " + i)

8         }

9     }

10 }

复制代码

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4         for (int i = 0i <100i++) {

5             System.out.println(Thread.currentThread().getName() + " " + i)

6             if (i == 30) {

7                 Runnable myRunnable = new MyRunnable()// 创建一个Runnable实现类的对象

8                 Thread thread1 = new Thread(myRunnable)// 将myRunnable作为Thread target创建新的线程

9                 Thread thread2 = new Thread(myRunnable)

10                 thread1.start()// 调用start()方法使得线程进入就绪状态

11                 thread2.start()

12             }

13         }

14     }

15 }

复制代码

相信以上两种创建新线程的方式大家都很熟悉了,那么Thread和Runnable之间到底是什么关系呢?我们首先来看一下下面这个例子。

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4         for (int i = 0i <100i++) {

5             System.out.println(Thread.currentThread().getName() + " " + i)

6             if (i == 30) {

7                 Runnable myRunnable = new MyRunnable()

8                 Thread thread = new MyThread(myRunnable)

9                 thread.start()

10             }

11         }

12     }

13 }

14

15 class MyRunnable implements Runnable {

16     private int i = 0

17

18     @Override

19     public void run() {

20         System.out.println("in MyRunnable run")

21         for (i = 0i <100i++) {

22             System.out.println(Thread.currentThread().getName() + " " + i)

23         }

24     }

25 }

26

27 class MyThread extends Thread {

28

29     private int i = 0

30  

31     public MyThread(Runnable runnable){

32         super(runnable)

33     }

34

35     @Override

36     public void run() {

37         System.out.println("in MyThread run")

38         for (i = 0i <100i++) {

39             System.out.println(Thread.currentThread().getName() + " " + i)

40         }

41     }

42 }

复制代码

同样的,与实现Runnable接口创建线程方式相似,不同的地方在于

1 Thread thread = new MyThread(myRunnable)

那么这种方式可以顺利创建出一个新的线程么?答案是肯定的。至于此时的线程执行体到底是MyRunnable接口中的run()方法还是MyThread类中的run()方法呢?通过输出我们知道线程执行体是MyThread类中的run()方法。其实原因很简单,因为Thread类本身也是实现了Runnable接口,而run()方法最先是在Runnable接口中定义的方法。

1 public interface Runnable {

2  

3     public abstract void run()

4  

5 }

我们看一下Thread类中对Runnable接口中run()方法的实现:

复制代码

@Override

public void run() {

if (target != null) {

target.run()

}

}

复制代码

也就是说,当执行到Thread类中的run()方法时,会首先判断target是否存在,存在则执行target中的run()方法,也就是实现了Runnable接口并重写了run()方法的类中的run()方法。但是上述给到的列子中,由于多态的存在,根本就没有执行到Thread类中的run()方法,而是直接先执行了运行时类型即MyThread类中的run()方法。

3.使用Callable和Future接口创建线程。具体是创建Callable接口的实现类,并实现clall()方法。并使用FutureTask类来包装Callable实现类的对象,且以此FutureTask对象作为Thread对象的target来创建线程。

看着好像有点复杂,直接来看一个例子就清晰了。

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4

5         Callable<Integer>myCallable = new MyCallable()   // 创建MyCallable对象

6         FutureTask<Integer>ft = new FutureTask<Integer>(myCallable)//使用FutureTask来包装MyCallable对象

7

8         for (int i = 0i <100i++) {

9             System.out.println(Thread.currentThread().getName() + " " + i)

10             if (i == 30) {

11                 Thread thread = new Thread(ft)  //FutureTask对象作为Thread对象的target创建新的线程

12                 thread.start()                     //线程进入到就绪状态

13             }

14         }

15

16         System.out.println("主线程for循环执行完毕..")

17      

18         try {

19             int sum = ft.get()           //取得新创建的新线程中的call()方法返回的结果

20             System.out.println("sum = " + sum)

21         } catch (InterruptedException e) {

22             e.printStackTrace()

23         } catch (ExecutionException e) {

24             e.printStackTrace()

25         }

26

27     }

28 }

29

30

31 class MyCallable implements Callable<Integer>{

32     private int i = 0

33

34     // 与run()方法不同的是,call()方法具有返回值

35     @Override

36     public Integer call() {

37         int sum = 0

38         for (i <100i++) {

39             System.out.println(Thread.currentThread().getName() + " " + i)

40             sum += i

41         }

42         return sum

43     }

44

45 }

复制代码

首先,我们发现,在实现Callable接口中,此时不再是run()方法了,而是call()方法,此call()方法作为线程执行体,同时还具有返回值!在创建新的线程时,是通过FutureTask来包装MyCallable对象,同时作为了Thread对象的target。那么看下FutureTask类的定义:

1 public class FutureTask<V>implements RunnableFuture<V>{

2  

3     //....

4  

5 }

1 public interface RunnableFuture<V>extends Runnable, Future<V>{

2  

3     void run()

4  

5 }

于是,我们发现FutureTask类实际上是同时实现了Runnable和Future接口,由此才使得其具有Future和Runnable双重特性。通过Runnable特性,可以作为Thread对象的target,而Future特性,使得其可以取得新创建线程中的call()方法的返回值。

执行下此程序,我们发现sum = 4950永远都是最后输出的。而“主线程for循环执行完毕..”则很可能是在子线程循环中间输出。由CPU的线程调度机制,我们知道,“主线程for循环执行完毕..”的输出时机是没有任何问题的,那么为什么sum =4950会永远最后输出呢?

原因在于通过ft.get()方法获取子线程call()方法的返回值时,当子线程此方法还未执行完毕,ft.get()方法会一直阻塞,直到call()方法执行完毕才能取到返回值。

上述主要讲解了三种常见的线程创建方式,对于线程的启动而言,都是调用线程对象的start()方法,需要特别注意的是:不能对同一线程对象两次调用start()方法。

你好,本题已解答,如果满意

请点右下角“采纳答案”。

总的结论:java是线程安全的,即对任何方法(包括静态方法)都可以不考虑线程冲突,但有一个前提,就是不能存在全局变量。如果存在全局变量,则需要使用同步机制。\x0d\x0a\x0d\x0a如下通过一组对比例子从头讲解:\x0d\x0a 在多线程中使用静态方法会发生什么事?也就是说多线程访问同一个类的static静态方法会发生什么事?是否会发生线程安全问题?\x0d\x0apublic class Test {\x0d\x0apublic static void operation(){\x0d\x0a// ... do something\x0d\x0a}\x0d\x0a}\x0d\x0a 事实证明只要在静态函数中没有处理多线程共享数据,就不存在着多线程访问同一个静态方法会出现资源冲突的问题。下面看一个例子:\x0d\x0apublic class StaticThread implements Runnable {\x0d\x0a@Override\x0d\x0apublic void run() {\x0d\x0a// TODO Auto-generated method stub\x0d\x0aStaticAction.print()\x0d\x0a}\x0d\x0apublic static void main(String[] args) {\x0d\x0afor (int i = 0i 回答于 2022-12-11

在JAVA平台 实现异步调用的角色有如下三个角色:调用者 提货单 真实数据一个调用者在调用耗时操作 不能立即返回数据时 先返回一个提货单 然后在过一断时间后凭提货单来获取真正的数据 去蛋糕店买蛋糕 不需要等蛋糕做出来(假设现做要很长时间) 只需要领个提货单就可以了(去干别的事情) 等到蛋糕做好了 再拿提货单取蛋糕就可以了 public class Main { public static void main(String[] args) {

System out println( main BEGIN )

Host host = new Host()

Data data = host request( A )

Data data = host request( B )

Data data = host request( C )

System out println( main otherJob BEGIN )

try {

Thread sleep( )

} catch (InterruptedException e) {

}

System out println( main otherJob END )

System out println( data = + data getContent())

System out println( data = + data getContent())

System out println( data = + data getContent())

System out println( main END )

}

}

这里的main类就相当于 顾客 host就相当于 蛋糕店 顾客向 蛋糕店 定蛋糕就相当于 发请求request 返回的数据data是FutureData的实例 就相当于提货单 而不是真正的 蛋糕 在过一段时间后(sleep一段时间后) 调用data getContent() 也就是拿提货单获取执行结果

下面来看一下 顾客定蛋糕后 蛋糕店做了什么

public class Host {

public Data request(final int count final char c) {

System out println( request( + count + + c + ) BEGIN )

// ( ) 建立FutureData的实体

final FutureData future = new FutureData()

// ( ) 为了建立RealData的实体 启动新的线程

new Thread() {

public void run() {

//在匿名内部类中使用count future c

RealData realdata = new RealData(count c)

future setRealData(realdata)

}

} start()

System out println( request( + count + + c + ) END )

// ( ) 取回FutureData实体 作为传回值

return future

}

}

host( 蛋糕店 )在接到请求后 先生成了 提货单 FutureData的实例future 然后命令 蛋糕师傅 RealData去做蛋糕 realdata相当于起个线程去做蛋糕了 然后host返回给顾客的仅仅是 提货单 future 而不是蛋糕 当蛋糕做好后 蛋糕师傅才能给对应的 提货单 蛋糕 也就是future setRealData(realdata)

下面来看看蛋糕师傅是怎么做蛋糕的

建立一个字符串 包含count个c字符 为了表现出犯法需要花费一些时间 使用了sleep

public class RealData implements Data { private final String content

public RealData(int count char c) {

System out println( making RealData( + count + + c + ) BEGIN )

char[] buffer = new char[count]

for (int i = i <counti++) {

buffer[i] = c

try {

Thread sleep( )

} catch (InterruptedException e) {

}

}

System out println( making RealData( + count + + c + ) END )

ntent = new String(buffer)

}

public String getContent() {

return content

}

}

现在来看看 提货单 future是怎么与蛋糕 content 对应的:

public class FutureData implements Data { private RealData realdata = null

private boolean ready = false

public synchronized void setRealData(RealData realdata) {

if (ready) {

return// 防止setRealData被调用两次以上

}

this realdata = realdata

this ready = true

notifyAll()

}

public synchronized String getContent() {

while (!ready) {

try {

wait()

} catch (InterruptedException e) {

}

}

return realdata getContent()

}

}

顾客做完自己的事情后 会拿着自己的 提货单 来取蛋糕

System out println( data = + data getContent())

这时候如果蛋糕没做好 就只好等了

while (!ready) { try {

wait()

} catch (InterruptedException e) {

}

//等做好后才能取到

return realdata getContent()

程序分析

对于每个请求 host都会生成一个线程 这个线程负责生成顾客需要的 蛋糕 在等待一段时间以后 如果蛋糕还没有做好 顾客还必须等待 直到 蛋糕被做好 也就是

future setRealData(realdata)执行以后 顾客才能拿走蛋糕

每个线程只是专门负责制作特定顾客所需要的 蛋糕 也就是顾客A对应着蛋糕师傅A 顾客B对应着蛋糕师傅B 即使顾客B的蛋糕被先做好了 顾客A也只能等待蛋糕师傅A把蛋糕做好 换句话说 顾客之间没有竞争关系

lishixinzhi/Article/program/Java/gj/201311/27425