黑马程序员 java之多线程总结

---------------------------------------------------------------- android培训、java培训、期待与您交流! ----------------------------------------------------------------------------------------
线程是进程的分割,是计算机进行调度的基本单位,一个进程可以包含一个或多个线程,有了线程程序的运行效率变快了。在java中线程的定义,可以通过两种方法,一种是通过继承Thread类,另一种是通过实现Runnalbe接口。示例如下:

class Test3 {  public static void main(String[] args)  {   ThreadDemo t1=new ThreadDemo();   t1.start();   ThreadDemo2 td=new ThreadDemo2();   Thread t2=new Thread(td);   t2.start();  } } class ThreadDemo extends Thread//继承Thread类以实现进程的创建 {       public void run()       {    while(true)     {    System.out.println(Thread.currentThread().getName()+"方法一");     }        } }

class ThreadDemo2 implements Runnable//实现Runnable接口以实现进程的创建 {  public void run()  {   while(true)   {    System.out.println(Thread.currentThread().getName()+"方法二");   }  } }

 进程的开启只能用start()方法, 虽然类中的run()方法可以调用,但是并不会开启一个进程。

进程间的同步:

一种是通过同步代码块,另一种是通过同步函数

class Test3 
{
	public static void main(String[] args) 
	{
		ThreadDemo1 td1=new ThreadDemo1();
		Thread t1=new Thread(td1);
		Thread t2=new Thread(td1);
		Thread t3=new Thread(td1);
		t1.start();
		t2.start();
		t3.start();
	}
}
class ThreadDemo1 implements Runnable
{
	public void run()
	{
		int x=1000;
		while(x>0)
		{
			synchronized(Test3.class)
			{
				System.out.println(Thread.currentThread().getName()+"-----"+x--);
			}
		}
	}
	public void synchronized run()
	{	int x=1000;
		while(x>0)
		{
			System.out.println(Thread.currentThread().getName()+"-----"+x--);
		}
	}
}


 ---------------------------------------------------------------- android培训、java培训、期待与您交流! ----------------------------------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值