多线程

概述

  • 作用
  • 编程要点

作用

  • 实现程序并行执行,提高效率

编程要点

  • run()方法编写多线程,它是线程的主体,当启动线程时,会执行线程的run()方法
  • start()方法启动多线程
  • sleep()方法用于休眠当前线程指定的毫秒数

示例

  • 示例1:
class testThread extends Thread{
	public testThread(String str){
		super(str);
	}
	public void run(){
		for (int i = 0; i < 3; i++) {
			System.out.println(getName()+" Now running");
			try {
				sleep(1000);
			} catch (InterruptedException e) {
			}
			System.out.println(getName()+" End");
		}
	}
}

public class Hmain {
	public static void main(String[] args) {
		testThread thread1 = new testThread("Thread1");
		testThread thread2 = new testThread("Thread2");
                System.out.println(white.getId());
		System.out.println(black.getId());
		System.out.println(white.getName());
		System.out.println(black.getName());
		thread1.start();
		thread2.start();
	}
}
  • 示例2:
public class ThreadDemo extends Thread{
	private String name=null;
	public ThreadDemo(String name){
		this.name=name;
	}
	public void run() {
		while(true){
			System.out.println(name+": Now running");
			try {
				Thread.sleep((int)(Math.random()*10000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
		Thread white=new ThreadDemo("white");
		Thread black=new ThreadDemo("\tblack");
		white.start();
		black.start();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值