以前多线程基础比较差,现在开始恶补。作为多线程的开门篇,多线程的实现是最基本的,也是java程序员闭着眼睛都应该可以实现的。
话不多说,直接上代码:
package day01;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* Multi-threaded alternate printing of numbers
*
* @author WEI 哥
*
*/
public class Fibonacci {
public static <V> void main(String[] args) {
/*
* TestThread thread1=new TestThread(); thread1.setName("线程1"); thread1.start();
*
* TestThread thread2=new TestThread(); thread2.setName("线程2"); thread2.start();
*/
/*
* TestThread2 thread21=new TestThread2(); new
* Thread(thread21.runnable).start();
*
* TestThread2 thread22=new TestThread2(); new
* Thread(thread22.runnable).start();
*/
Callable<V> thread31 = new TestThread3<V>();
FutureTask<V> task = new FutureTask<V>(thread31);
Thread thread = new Thread(task);
thread.start();
Callable<V> thread32 = new TestThread3<V>();
FutureTask<V> task2 = new FutureTask<V>(thread32);
Thread thread2 = new Thread(task2);
thread2.start();
}
}
class TestThread extends Thread {
static int r = 0;
public void run() {
synchronized (TestThread.class) {
for (int i = 0; i < 5; i++) {
TestThread.class.notify();
System.out.println(Thread.currentThread().getName() + " " + r);
r++;
try {
TestThread.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class TestThread2 implements Runnable {
static int r = 0;
@Override
public void run() {
synchronized (TestThread.class) {
for (int i = 0; i < 5; i++) {
TestThread.class.notify();
System.out.println(Thread.currentThread().getName() + " " + r);
r++;
try {
TestThread.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class TestThread3<V> implements Callable<V> {
static int r = 0;
@Override
public V call() throws Exception {
synchronized (TestThread.class) {
for (int i = 0; i < 5; i++) {
TestThread.class.notify();
System.out.println(Thread.currentThread().getName() + " " + r);
r++;
try {
TestThread.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
}