标签:
一、为什么需要并发编程
如果是单线程的编程,如果一个程序遇到阻塞的情况,比如需要等待i/o的某个事件发生,才能执行程序。这样就造成了影响了下面的程序的运行。
并发,就是在进程中,采用多个任务进行处理,每个任务由操作系统来回切换。
这样就感觉像很多任务同时执行一样。
二、基本的线程机制
1、定义任务
定义一个类,实现Runnable()接口,在Runnable()接口中定义了run()方法,我们可以把要执行的事件写在run()方法中。
而run()中任务的运行,需要将其放在Thread构造器中。
通过start方法运行thread后,就会运行在thread中的任务。
class task1 implements Runnable
{
 
   public void run()
   {
	   for(int x=0;x<=10;x++)
	   {
		   for(int y=0;y<=99999999;y++){}
			System.out.println(Thread.currentThread().getName()+"....x="+x);
	   }
	  }
   
}
class task2 implements Runnable
{
 
   public void run()
   {
	   for(int z=0;z<=10;z++)
	   {
		   for(int y=0;y<=99999999;y++){}
			System.out.println(Thread.currentThread().getName()+"....z="+z);
	   }
	  }
   
}
public class hello {
public static void main(String[] args){
	
	task1 t1= new task1(); 
	task2 t2 = new task2();
	Thread nt1 = new Thread(t1);
	Thread nt2 = new Thread(t2);
	nt1.start();
	nt2.start();
		
	}
}标签:
原文地址:http://blog.csdn.net/a879365197/article/details/46607267