Java(18):多线程的启用

日期:2017/11/10

      Java常用的多线程方法有两个:

               (1)继承Thread类+重写run方法,在mian()中用start()方法调用启动;

代码例子如下:

package com.thread;

public class MyThread  extends Thread{
	private String name;
	
	public MyThread(String name){
		this.name = name;
	}
	
	public void run(){
		for (int i=10; i<1010; i++){
			System.out.println(name +": "+i);
		}
//		super.run();
	}

}
package com.thread;


public class ThreadTest {


	public static void main(String[] args) {
		MyThread thread = new MyThread("Thread Test One");
		MyThread threadtwo = new MyThread("Thread Test Two");
		//线程的启动不是通过run方法(调用)
		//thread.run();
		thread.start();
		threadtwo.start();
		System.out.println("**********");
		
		//another way to realize Thread
		MyRunnable myrunnable1 = new MyRunnable("A");
		MyRunnable myrunnable2 = new MyRunnable("B");
		Thread t1 = new Thread(myrunnable1);
		Thread t2 = new Thread(myrunnable2);
		t1.start();
		t2.start();
	}


}



               (2)实现Runnable接口+重写run方法,在mian()中新建Thread引用并使用start()方法调用启动;

代码例子:

package com.thread;

class ThreadDemo implements Runnable{
	private String name;
	public ThreadDemo(String name){
		this.name = name;
	}
	public void run() {
		for (int i = 0; i<50; i++){
			try{
				Thread.sleep(1000);
				System.out.println(Thread.currentThread().getName()+": "+i);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		
	}
	
}

public class ThreadTestThree {

	public static void main(String[] args) {
		//使用匿名对象,创建线程更加方便
		Thread t1 = new Thread(new ThreadDemo("A"),"A");
		Thread t2 = new Thread(new ThreadDemo("B"),"B");
		Thread t3 = new Thread(new ThreadDemo("C"),"C");
//		t1.setPriority(Thread.MAX_PRIORITY);
		t1.setPriority(Thread.MIN_PRIORITY);
		t2.setPriority(Thread.NORM_PRIORITY);
		t3.setPriority(Thread.MAX_PRIORITY);
		t1.start();
		t2.start();
		t3.start();
		
	}

}

     PS:一般来说,使用Runnable接口实现的方法更加灵活,因为接口能够多个实现,更加易于满足业务增长的需求;但是使用继承的方法,则是不能扩展更多的功能了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值