JAVA学习笔记--多线程(一)

多线程--在一个程序中允许同时执行多个任务,

线程(Thread)指的是一个任务从头至尾的执行流

实现步骤:
1.创建任务和对象
首先创建一个任务类,任务类必须实现Runnable接口,并且重写run()方法

2.任务类在线程中执行
线程类包括创建线程的构造方法和控制线程的很多有用的方法


3.JAVA虚拟机通过调用任务的run()方法执行任务。

实例:
目标说明:使用两个线程,一个线程打印字母‘A’100次,一个线程打印数字‘9’100次
步骤1:
创建两个任务类,分别用于打印字母和数字(实现Runable接口,重写run()方法)
public class PrintChar implements Runnable {
	char ch;
	int count=0;
	public PrintChar(char ch,int count){
	    this.ch=ch;
	    this.count=count;
		}
	public void run() {
		for(int i=0;i<count;i++){
			System.out.print(" "+ch);
		}
	}
}
public class PrintNum implements Runnable{
	int num;
	int count;
 public PrintNum (int Num,int count){
	 this.num=Num;
	 this.count=count;
 }
 @Override
public void run() {
	// TODO Auto-generated method stub
 for(int i=0;i<count;i++){
	 System.out.print(num);
     }	
   }
}

步骤2:
在主函数中实例化任务对象和一个线程实例,创建任务的线程,然后调用start()方法告诉JVM该线程准备执行。
public class Print {
   public static void main(String[] args) {
		Runnable pc=new PrintChar('A', 100);
		Runnable pn=new PrintNum(9, 100);
		
	    Thread th1=new Thread(pc);
	    Thread th2=new Thread(pn);
	    
	    th1.start();
	    th2.start();
     }
}


部分输出结果如下:
 A9 A9 A9999 A9 A9 A9 A9 A9 A A A9 A999999 A99999 A999 A9 A9 A A A9 A A A9 A A A A A A A99 A A A9 A9 A9 A99 A9 A9 A9 A9 A99 A9 A9 A99 A999 A99 A9 A9 A9 A9 A A A9 A A A A A A A A A A A A A A

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值