Java多线程的实现这里介绍三个
- 继承Thread,重写run方法
- 实现Runnable接口,重写run方法,将对象装配进Thread对象
- 实现Callable接口,重写call方法,可以带返回值,将对象装配进FutureTask中,再将FutureTask对象装配进Thread中
Thread
MyThread类
package com.igeek.learn;
public class MyThread extends Thread{
int num = 100;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName()+":"+ --num);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
TestThread
package com.igeek.learn;
public class TestThread {
public static void main(String[] args) {
MyThread th = new MyThread();
MyThread th1 = new MyThread();
th.start();
th1.start();
}
}
Runnable
MyRunnable类
package com.igeek.learn;
public class MyRunnable implements Runnable{
int num = 100;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+num--);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
TestRunnable
package com.igeek.learn;
public class TestRunnable {
public static void main(String[] args) {
MyRunnable my = new MyRunnable();
Thread thread = new Thread(my,"线程1");
thread.start();
Thread thread1 = new Thread(my,"线程2");
thread1.start();
}
}
特别注明,由于这里线程并没有上锁,所以会脏数据,导致每次运行结果都有可能不同,如何上锁我们放在下一次去说明。
Callable
MyCallable
package com.igeek.learn;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+ i);
Thread.sleep(1000);
}
return "I Love Java";
}
}
TestCallable
package com.igeek.learn;
import java.util.concurrent.FutureTask;
public class TestCallable {
public static void main(String[] args) throws Exception{
MyCallable myCallable = new MyCallable();
FutureTask<String> fu = new FutureTask<>(myCallable);
Thread th = new Thread(fu,"线程1");
th.start();
FutureTask<String> fu1 = new FutureTask<>(myCallable);
Thread th1 = new Thread(fu1,"线程2");
th1.start();
System.out.println(fu.get());
System.out.println(fu1.get());
}
}