19 线程

1Java中如果我们自己没有产生线程,那么系统就会给我们产生一个线程(主线程,main方法就在主线程上运行),我们的程序都是由线程来执行的。
进程:执行中的程序(程序是静态的概念,进程是动态的概念)。
2线程的实现有两种方式,第一种方式是继承Thread类,然后重写run方法;第二种是实现Runnable接口,然后实现其run方法。

3 将我们希望线程执行的代码放到run方法中,然后通过start方法来启动线程,start方法首先为线程的执行准备好系统资源,然后再去调用run方法。当某个类继承了Thread类之后,该类就叫做一个线程类。


如果使用run方法,就相当于一个类在执行run方法,不会实现线程

public class ThreadTest1
{
	public static void main(String[] args)
	{
		Thread mythread = new MyThread();
		mythread.start();

	}
}

class MyThread extends Thread
{
	@Override
	public void run()
	{
		System.out.println("I miss bingjia");
	}
}




4 一个进程至少要包含一个线程。
5对于单核CPU来说,某一时刻只能有一个线程在执行(微观串行),从宏观角度来看,多个线程在同时执行(宏观并行)。

6 对于双核或双核以上的CPU来说,可以真正做到微观并行。



7
1) Thread类也实现了Runnable接口,因此实现了Runnable接口中的run方法;

2) 当生成一个线程对象时,如果没有为其设定名字,那么线程对象的名字将使用如下形式:Thread-number,该number将是自动增加的,并被所有的Thread对象所共享(因为它是static的成员变量)。

Java源码

public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }

 public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }


3) 当使用第一种方式来生成线程对象时,我们需要重写run方法,因为Thread类的run方法此时什么事情也不做。

4) 当使用第二种方式来生成线程对象时,我们需要实现Runnable接口的run方法,然后使用new Thread(new MyThread())(假如MyThread已经实现了Runnable接口)来生成线程对象,这时的线程对象的run方法就会调用MyThread类的run方法,这样我们自己编写的run方法就执行了。

public class ThreadTest2
{

//方法1
	Thread thread = new Thread(new mythread());
<span style="white-space:pre">		</span>thread.start();
//方法2 使用匿名内部类
<span style="white-space:pre">		</span>Thread thread2=new Thread(new Runnable()
<span style="white-space:pre">		</span>{
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>@Override
<span style="white-space:pre">			</span>public void run()
<span style="white-space:pre">			</span>{
<span style="white-space:pre">				</span>for (int i=0;i<10;i++)
<span style="white-space:pre">				</span>{
<span style="white-space:pre">					</span>System.out.println("线程2:"+i);
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>});
}

class mythread implements Runnable
{

	@Override
	public void run()
	{
		for (int i = 0; i < 100; i++)
		{
			System.out.println("i miss bingjia" + i);
		}

	}
}





8关于成员变量与局部变量:如果一个变量是成员变量,那么多个线程对同一个对象的成员变量进行操作时,他们对该成员变量是彼此影响的(也就是说一个线程对成员变量的改变会影响到另一个线程)。

9如果一个变量是局部变量,那么每个线程都会有一个该局部变量的拷贝,一个线程对该局部变量的改变不会影响到其他的线程。

public class ThreadTest3
{
	public static void main(String[] args)
	{
		Runnable r = new HelloThread();
		
		Thread t1 = new Thread(r);
		
		//r = new HelloThread();
		
		Thread t2 = new Thread(r);
		
		t1.start();
		t2.start();
	}
}

class HelloThread implements Runnable
{
	int i;
	
	@Override
	public void run()
	{
		int i = 0;
		
		while(true)
		{
			System.out.println("number: " + this.i++);
			
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			if(50 == this.i)
			{
				break;
			}
		}
	}
}

10停止线程的方式:不能使用Thread类的stop方法来终止线程的执行。一般要设定一个变量,在run方法中是一个循环,循环每次检查该变量,如果满足条件则继续执行,否则跳出循环,线程结束。

11 不能依靠线程的优先级来决定线程的执行顺序。系统会根据等待时间改变线程的优先级。


12 synchronized关键字:当synchronized关键字修饰一个方法的时候,该方法叫做同步方法。

public class FetchMoney
{
	public static void main(String[] args)
	{
		Bank bank = new Bank();
		
		Thread t1 = new MoneyThread(bank); // 柜台
		
		//bank = new Bank();
		
		Thread t2 = new MoneyThread(bank); // 取款机
		
		t1.start();
		t2.start();
	}
}

class Bank
{
	private int money = 1000;
	
	public synchronized int getMoney(int number)
	{
		if(number < 0)
		{
			return -1;
		}
		else if(number > money)
		{
			return -2;
		}
		else if(money < 0)
		{
			return -3;
		}
		else
		{
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			money -= number;
			
			System.out.println("left money: " + money);
			
			return number;
		}		
	}
}

class MoneyThread extends Thread
{
	private Bank bank;
	
	public MoneyThread(Bank bank)
	{
		this.bank = bank;
	}
	
	@Override
	public void run()
	{
		System.out.println(bank.getMoney(800));
	}
}

13 Java中的每个对象都有一个锁(lock)或者叫做监视器(monitor),当访问某个对象的synchronized方法时表示将该对象上锁,此时其他任何线程都无法再去访问该synchronized方法了,直到之前的那个线程执行方法完毕后(或者是抛出了异常),那么将该对象的锁释放掉,其他线程才有可能再去访问该synchronized方法。

14 如果一个对象有多个synchronized方法,某一时刻某个线程已经进入到了某个synchronized方法,那么在该方法没有执行完毕前,其他线程是无法访问该对象的任何synchronized方法的。


public class ThreadTest4
{
	public static void main(String[] args)
	{
		Example example = new Example();
		
		Thread t1 = new TheThread(example);
		
		example = new Example();
		
		Thread t2 = new TheThread2(example);
		
		t1.start();
		t2.start();
	}
}

class Example
{
	public synchronized void execute()
	{
		for(int i = 0; i < 20; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			System.out.println("hello: " + i);
		}
	}
	
	public synchronized static void execute2()
	{
		for(int i = 0; i < 20; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			System.out.println("world: " + i);
		}
	}
}


class TheThread extends Thread
{
	private Example example;
	
	public TheThread(Example example)
	{	
		this.example = example;
	}
	
	@Override
	public void run()
	{
		this.example.execute();
	}
}

class TheThread2 extends Thread
{
	private Example example;
	
	public TheThread2(Example example)
	{	
		this.example = example;
	}
	
	@Override
	public void run()
	{
		this.example.execute2();
	}
}


15如果某个synchronized方法是static的,那么当线程访问该方法时,它锁的并不是synchronized方法所在的对象,而是synchronized方法所在的对象所对应的Class对象,因为Java中无论一个类有多少个对象,这些对象会对应唯一一个Class对象,因此当线程分别访问同一个类的两个对象的两个static,synchronized方法时,他们的执行顺序也是顺序的,也就是说一个线程先去执行方法,执行完毕后另一个线程才开始执行。
16. synchronized块,写法:
synchronized(object)
{
}
表示线程在执行的时候会对object对象上锁。

public class ThreadTest2
{

	public static void main(String[] args)
	{
		exmaple exmaple=new exmaple();
		
		mythread tMythread1=new mythread(exmaple);
		//exmaple=new exmaple();
		mythread tMythread2=new mythread(exmaple);
		tMythread1.start();
		tMythread2.start();
		
		
	}
}

class exmaple
{
	public void sayMiss()
	{
		synchronized (this)
		{
			for (int i = 0; i < 50; i++)
			{
				System.out.println("I miss you bingjia" + i);
			}

		}
	}
}

class mythread extends Thread
{
	exmaple exmaple;
	public mythread(exmaple e)
	{		
		this.exmaple=e;
	}
	@Override
	public void run()
	{
		exmaple.sayMiss();
	}
}

17. synchronized方法是一种粗粒度的并发控制,某一时刻,只能有一个线程执行该synchronized方法;synchronized块则是一种细粒度的并发控制,只会将块中的代码同步,位于方法内、synchronized块之外的代码是可以被多个线程同时访问到的

18wait与notify方法都是定义在Object类中,而且是final的,因此会被所有的Java类所继承并且无法重写。这两个方法要求在调用时线程应该已经获得了对象的锁,因此对这两个方法的调用需要放在synchronized方法或块当中。当线程执行了wait方法时,它会释放掉对象的锁。

public class NotifyTest
{
	public static void main(String[] args)
	{

		Say songxu=new Say();
		
		threadDislike dislike=new threadDislike(songxu);
		
		threadSaylike liSaylike=new threadSaylike(songxu );
		
		dislike.start();
		liSaylike.start();
	}

}

class Say
{

	public int count = 0;

	public synchronized void like()
	{
		while (count == 1)
		{
			try
			{
				wait();
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.out.println("I miss you WangBingjia");
		count++;
		notify();
	}

	public synchronized void SayDislike()
	{
		while (count == 0)
		{
			try
			{
				wait();
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.out.println("I don't like you!");
		count--;
		notify();

	}
}

class threadSaylike extends Thread
{
	Say say;

	public threadSaylike(Say say)
	{
		this.say = say;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run()
	{try
	{
		Thread.sleep((long)Math.random()*1000);
	}
	catch (InterruptedException e)
	{
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		for (int i=0;i<20;i++)
		{
			
			say.like();
		}
	}
}
class threadDislike extends Thread
{
	Say say;

	public threadDislike(Say say)
	{
		this.say = say;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run()
	{
		try
		{
			Thread.sleep((long)Math.random()*1000);
		}
		catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i=0;i<20;i++)
		{
			
			say.SayDislike();
		}
	}
}



19. 另一个会导致线程暂停的方法就是Thread类的sleep方法,它会导致线程睡眠指定的毫秒数,但线程在睡眠的过程中是不会释放掉对象的锁的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值