下面要给大家介绍的就是一个很基础的内容,java异步,那么你知道java异步要怎样才能够实现吗?一起通过下面的java实例来了解一下吧。
下面的话,就给大家介绍2种实现多线程的异步处理方式。
一个是继承Thread,一个是实现Runnable。
下面直接来看示例。
一、继承Thread
代码:
public class testThread extends Thread { private String name; private int number = 5; public testThread(String name) { this.name = name; } public void run() { for (int i = 0; i < 100; i++) { if (number > 0) { System.out.println(this.name + "===" + number--); } } } public static void main(String args[]) { testThread t1 = new testThread("t1"); testThread t2 = new testThread("t2"); testThread t3 = new testThread("t3"); t1.start(); t2.start(); t3.start(); } }
二、实现Runnable
代码:
public class runnableTest implements Runnable { private String name; private int number = 5; public void run() { for (int i = 0; i < 100; i++) { if (number > 0) { System.out.println(Thread.currentThread() .getName() + "==" + number--); } } } public static void main(String[] args) { runnableTest test1 = new runnableTest(); runnableTest test2 = new runnableTest(); runnableTest test3 = new runnableTest(); Thread t1 = new Thread(test1, "t1"); Thread t2 = new Thread(test2, "t2"); Thread t3 = new Thread(test3, "t3"); t1.start(); t2.start(); t3.start(); } }
除了以上的2种方式之外,再一起来看看多线程共同执行同一个任务的方法吧。
代码:
public class runnableTest implements Runnable { private String name; private int number = 5; public void run() { for (int i = 0; i < 100; i++) { if (number > 0) { System.out.println(Thread.currentThread() .getName() + "==" + number--); } } } public static void main(String[] args) { runnableTest test1 = new runnableTest(); Thread t1 = new Thread(test1, "t1"); Thread t2 = new Thread(test1, "t2"); Thread t3 = new Thread(test1, "t3"); t1.start(); t2.start(); t3.start(); } }
对于java异步的内容你都了解了吗?java实现异步的方法还是比较简单的,希望上面的内容可以对你有所帮助呢。
你想成为一名java架构师吗?更多java架构师相关知识,可以继续来奇Q工具网了解学习哦。
推荐阅读: