java学习笔记 线程的实现与同步

2019.4.2

线程实现的两种方式

  1. 继承线程,复写其中的run方法
  2. 实现runnable接口,复写run方法
    使用:
MyThread target = new MyThread();
new Thread(taget).start();
//或者使用匿名 如下
    new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();

synchronized 同步操作

1. 同步代码块
声明一个互斥锁

    static Object lock = new Object();

在一个线程的run方法中

 @Override
    public void run() {
        while (true) {
			try {
			    sleep(10);
			} catch (InterruptedException e) {
			    e.printStackTrace();
			}
            synchronized (lock) {
              
                System.out.println(num);
                num++;
            }

        }
    }
  1. synchronized同步方法以及使用
/**
 * @author StarsOne
 * @date Create in  2019/4/6 0006 17:49
 * @description
 * 1.    编写一个线程类,创建三个该线程的实例对同一个共享的int型变量作同步的递增操作。并在控制台输出:0,1,2,3,4,5….。要求分别使用以下两种同步方式实现:
 * a)	使用synchronized同步块实现。对共享int型变量的同步访问。
 * b)	使用synchronized方法实现。对共享int型变量的同步访问。
 */
class HomeWork1 extends Thread {
    static int num = 0;//需要修改的共享变量
    String currentThreadName;//线程名
    static final Object object = new Object();//一个对象锁,必须要static和final关键字修饰
    
    public HomeWork1(String currentThreadName) {
        setDaemon(true);//设置为守护进程(子进程),主进程结束,子进程也结束
        this.currentThreadName = currentThreadName;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.changeNum(currentThreadName);
            
            //同步代码块
           /* synchronized (object) {
                System.out.println(currentThreadName+":"+num);
                num++;
            }*/

        }
    }


    //synchronized同步方法
    private static synchronized void changeNum(String name) {
        System.out.println(name+":"+num);
        num++;
    }
    
    public static void main(String[] args) {
        HomeWork1 thread1 = new HomeWork1("thread1");
        HomeWork1 thread2 = new HomeWork1("thread2");
        HomeWork1 thread3 = new HomeWork1("thread3");
        HomeWork1 thread4 = new HomeWork1("thread4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //2s秒结束主线程,其相关的子线程一并结束

    }
}

posted @ 2019-04-06 18:36  Stars-one  阅读(272)  评论(0编辑  收藏  举报