多线程
1 package com.xixi;
2
3 class Test{
4 public static void main(String[] args){
5 Thread t1 = new Thread(){
6 public void run(){
7 for(int i =0;i<10;i++) {
8 System.out.println(getName()+"aaaa");
9 }
10 }
11 };
12
13 Thread t2=new Thread(){
14 public void run(){
15 for(int i =0;i<10;i++) {
16 if (i==2){
17 try {
18 t1.join();
19 }catch (Exception e){
20 e.printStackTrace();
21 }
22 }
23 System.out.println(getName()+"bbbb");
24 }
25 }
26 };
27
28 t1.start();
29 t2.start();
30 }
31 }
13.同步代码块
实例:
1 package com.xixi;
2
3 class Test{
4 public static void main(String[] args){
5 Printer p=new Printer();
6 new Thread(){
7 public void run(){
8 p.print1();
9 }
10 }.start();
11 new Thread(){
12 public void run(){
13 p.print2();
14 }
15 }.start();
16 }
17 }
18
19 class Printer{
20 Object d=new Object();
21 public void print1(){
22 synchronized (d) {
23 System.out.println("A");
24 System.out.println("B");
25 System.out.println("C");
26 }
27 }
28
29 public void print2(){
30 synchronized (d) {
31 System.out.println("a");
32 System.out.println("b");
33 System.out.println("c");
34 }
35 }
36 }
14.同步方法
15.用同步代码块的方法解决实际问题
以下模拟火车站四个窗口共售卖100张票
1 package com.xixi;
2
3 class Test{
4 public static void main(String[] args){
5 new Seller().start();
6 new Seller().start();
7 new Seller().start();
8 new Seller().start();
9 }
10 }
11
12 class Seller extends Thread{
13 private static int ticket=100; //将票数设置为静态变量,这样保证了四个线程访问数据的同一性。
14 public void run(){
15 while (true){
16 //这里给代码块上锁,保证同步执行
17 synchronized (Seller.class) { //这里上的锁为保证统一,用的是Seller类的对象。
18 if (Seller.ticket == 0)
19 break;
20 //模拟实际的各类延迟
21 try {
22 Thread.sleep(10);
23 } catch (Exception e) {
24 e.printStackTrace();
25 }
26
27 System.out.println("这是" + getName() + "号窗口:第" + (ticket--) + "号票已卖出。");
28 }
29 }
30 }
31 }