java多线程机制是java中十分重要的内容,在面试过程中也是被经常问到的内容。
一.java使用多线程的方式
1.继承Thread类
package com.lql.thread;
public class MyTask5 extends Thread {
private static int count = 10;
public void run() {
while (count > 0) {
count--;
System.out
.println("currentThread:"+Thread.currentThread().getName() + "-->" + count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new MyTask5().start();
}
}
}
package com.lql.thread;对于是实现Runnable接口还是继承Thread类来实现多线程的问题,如果你的线程类已经继承了一个父类,那就不能再继承Thread了,就只能实现Runnable接口了。
public class MyTask2 implements Runnable{
private static int count = 10;
public MyTask2(){
}
@Override
public synchronized void run() {
// TODO Auto-generated method stub
while (count > 0){
count--;
System.out.println(count+"-->"+Thread.currentThread().getName());
Thread.yield();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 创建线程并设置线程优先级,优先级只是对于处理机进行线程调度的一种建议
* 各个线程在执行时,并不一定会遵照优先级的顺序,执行顺序与处理机以及线程
调度机制等诸多因素有关
* @param args
*/
public static void main(String[] args) {
Thread thread = new Thread(new MyTask2());
thread.setName("threa1");
thread.setPriority(3);
thread.start();
Thread thread2 = new Thread(new MyTask2());
thread2.setName("threa2");
thread2.setPriority(1);
thread2.start();
Thread thread3 = new Thread(new MyTask2());
thread3.setName("threa3");
thread3.setPriority(2);
thread3.start();
}
}
例子中run()方法执行一次循环之后,有一个Thread.yield()方法,yield()方法是作用是告诉处理器,我已经执行了一次完整周期,现在是线程切换的好时机,建议现在进行线程切换。至于处理器去不去进行线程切换,这就不一定了。
主线程中创建若干个子线程对象后,如果直接通过引用来调用子线程中的run()方法,就不会开启新线程,此时run()方法仍然是在主线程中执行的,与普通方法调用无异。
package com.lql.thread;
public class MyTask5 extends Thread {
private static int count = 10;
public void run() {
while (count > 0) {
count--;
System.out
.println(Thread.currentThread().getName() + "-->" + count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//for (int i = 0; i < 5; i++) {
//new MyTask5().start();
//}
for(int i = 0 ; i < 5 ; i++){
Thread thread = new MyTask5();
thread.run();
}
}
}
</pre><pre name="code" class="java">currentThread:main-->9currentThread:main-->8currentThread:main-->7currentThread:main-->6currentThread:main-->5currentThread:main-->4currentThread:main-->3currentThread:main-->2currentThread:main-->1currentThread:main-->0
二、Callable接口
从上边的例子中可以看到,线程类中的run()方法并没有返回值,如果有时我们希望在子线程中执行之后有一个返回值,那我们就可以是使用Callable接口来实现子线程。
package com.lql.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyTask6 implements Callable<Integer> {
private int num = 0;
public MyTask6(int n){
this.num = n;
}
public MyTask6(){
}
/**
* 递归求阶乘
* @param n
* @return
*/
public int Factorial(int n){
if(n <= 0){
return 1;
}
if(n == 1){
return 1;
}
return n * Factorial(n - 1);
}
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName());
return Factorial(num);
}
public static void main(String[] args) {
MyTask6 myTask6 = new MyTask6(5);
ExecutorService exec = Executors.newFixedThreadPool(1);
Future<Integer> future = exec.submit(myTask6);//Future是一个线程返回值的容器
exec.shutdown();
try {
System.out.println(future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Runable接口实现线程的方式与Callable接口实现多线程的方式有如下区别:
1.Runnable提供执行子任务逻辑是run()方法,Callable接口提供的方法的是call()方法
2.使用Runnable的线程不能有返回值,Callable接口可以有返回值
3.run()无法抛出异常,call()方法可以抛出异常