1. /*
2. 多线程 同步函数 练习
3.
4. 1,明确哪些代码是多线程运行代码
5. 2,明确共享数据
6. 3,明确多线程运行代码中哪些语句是操作共享数据的
7.
8.
9. */
10.
11. class Bank
12. {
13. private int sum =0;
14. //Object obj = new Object();
15. public synchronized void add(int a)//同步函数
16. {
17. // synchronized(obj){//同步代码块
18. sum+=a;
19. try{Thread.sleep(40);}catch(Exception e){}
20. "sum = "+ sum);
21. // }
22. }
23.
24. }
25.
26. class Client implements Runnable
27. {
28. private Bank b = new Bank();
29.
30. public void run()
31. {
32. for(int i=0;i<3;i++)
33. {
34. 100);
35. }
36. }
37. }
38.
39. class Test
40. {
41.
42. public static void main(String []args)
43. {
44. new Client();
45. new Thread(c);
46. new Thread(c);
47.
48. t1.start();
49. t2.start();
50. }
51. }

//**************************************************************

package com.ygl;
/*
* 卖票属于多线程,卖票程序要被多个线程所执行,要写在run方法中
*
*/
public class Ticket implements Runnable {
/*
* 创建线程第二种方式:实现Runnable接口
* 步骤:
* 1.定义类实现Runnable接口
* 2.覆盖Runnable接口 中的 run方法
* 将线程要运行的代码存放在该run方法中.
* 3.通过Thread类建立线程对象
* 4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数
*
* 5.调用Thread类的start方法开启线程并调用Runnable接口的子类的run方法
*
* 实现方式和继承方式区别?
* 实现方式避免了单继承的局限性,在定义线程时建议使用实现方式
* 并且资源可以被共享.
* 区别:
* 继承Thread:线程代码存放在子类run方法中.
* 实现Runnable:线程代码存放在接口子类run方法中.
*
* java对于多线程的安全问题提供了专业的解决方式:
* 就是同步代码块.
* synchronized(对象){
*
* 需要被同步的代码
*
* }
*
*/


private int ticketCount=100;


@Override
public void run() {
// TODO Auto-generated method stub
while(true){
show();
}
}

public synchronized void show(){
if(ticketCount>0){
System.out.println(Thread.currentThread().getName()+" sale:"+ticketCount--);
}
}


public static void main(String[] args) {
//Runnable实现类
Ticket t=new Ticket();
//而只有线程或其子类才能开启线程执行run方法
//多线程共享t的属性
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}