java实现多线程 例子

Thread 方法

下表列出了Thread类的一些重要方法:

序号 方法描述
1 public void start()
使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
2 public void run()
如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。
3 public final void setName(String name)
改变线程名称,使之与参数 name 相同。
4 public final void setPriority(int priority)
更改线程的优先级。
5 public final void setDaemon(boolean on)
将该线程标记为守护线程或用户线程。
6 public final void join(long millisec)
等待该线程终止的时间最长为 millis 毫秒。
7 public void interrupt()
中断线程。
8 public final boolean isAlive()
测试线程是否处于活动状态。

用户线程:无论主线线程是否结束,用户线程都会跑完。非用户线程在主线程跑完后会自动终止

通过实现接口方式,实现多线程

/**
 * 通过实现接口方式,实现多线程
 * @author Administrator
 *
 */
public class ThreadConuer{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread t = new Thread(new PrintString("hello",1000));
	    t.setDaemon(true);	//用户线程
	    t.setName("hello");	//修改线程名字
		t.start();
	}
}
/**
 * 打印字符串n次
 * @author Administrator
 *
 */
class PrintString implements Runnable {
	String str = null;
	int n;
	public PrintString (String s,int n){
		str = s;
		this.n = n;
	}
	@Override
    public void run() {
		for(int i=0;i<n;i++)
          System.out.println(str);
    }
 }

通过继承方法。实现多线程

/**
 *  通过继承方法。实现多线程
 * @author Administrator
 *
 */
public class ThreadInherit{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread t = new PrintString2("Hello",1000);
	    t.setDaemon(true);	//用户线程
	    t.setName("hello");	//修改线程名字
		t.start();
	}
}

/**
 * 打印字符串n次
 * @author Administrator
 *
 */
class PrintString2 extends Thread{
	String str = null;
	int n;
	public PrintString2 (String s,int n){
		str = s;
		this.n = n;
	}
	
	@Override
    public void run(){
		for(int i=0;i<n;i++)
          System.out.println(str);
    }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值