三种方式实现多线程交替打印数字

以前多线程基础比较差,现在开始恶补。作为多线程的开门篇,多线程的实现是最基本的,也是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;
	}

}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值