Java笔记(二)

时间:2022-02-02 09:08:49

10.

  public  protected default private
同一个类中
同一个包中  
子类    
不同包中      

11. 线程:

 static Thread currentThread():获取当前线程对象

 getName():获取线程名称

 设置线程名称:setName()或者构造函数

 创建线程的方式:

  1. 继承Thread类

    (1)定义类,继承Thread

    (2)复写Thread类中的void run()方法(因为Thread类用于描述线程,该类就定义了一个功能,用于存储线程要运行的代码。该存储功能就是run方法。)

    (3)调用线程的start方法,该方法能启动线程,并能调用run方法

    注:对象.run()仅仅是对象调用方法。而线程创建了,并没有运行;

      对象.start()开启线程并执行该线程的run方法

  2. 实现Runnable接口

    (1)定义类,实现Runnable接口

    (2)覆盖Runnable接口中的run方法。将线程要运行的代码存放在该run方法中

    (3)通过Thread类建立线程对象

    (4)将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。因为,自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去执行指定对象的run方法,就必须明确该run方法所属的对象。

    (5)调用Thread类的start方法开启线程,并调用Runnable接口子类的run方法

  实现方式与继承方式的区别:

   实现方式好处:避免了单继承的局限性。在定义线程时,建议使用实现方式。

   继承Thread:线程代码存放在Thread子类run方法中;实现Runnable:线程代码存放在接口的子类的run方法。

 同步函数的锁是this;静态同步函数的锁是Class对象(类名.class)

 死锁:例:

 class DeadLock implements Runnable{
private boolean flag;
DeadLock(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
while(true){
synchronized(Lock.locka){
System.out.println("if locka");
synchronized(Lock.lockb){
System.out.println("if lockb");
}
}
}
}
else{
while(true){
synchronized(Lock.lockb){
System.out.println("else lockb");
synchronized(Lock.locka){
System.out.println("else locka");
}
}
}
}
}
} class Lock{
public static Object locka = new Object();
public static Object lockb = new Object();
} public class Demo{
public static void main(String[] args) {
Thread t1 = new Thread(new DeadLock(true));
Thread t2 = new Thread(new DeadLock(false));
t1.start();
t2.start();
}
}

 wait()  notify()  notifyAll():

  都使用在同步中,因为要对持有监视器(锁)的线程操作,只有同步才具有锁。

  这些方法在操作同步中线程时,都必须要标识它们所操作线程持有的锁。只有同一个锁上的被等待线程,可以被同一个锁上的notify()唤醒,不可以对不同锁中的线程进行唤醒。也就是说,等待和唤醒必须是同一个锁。而锁可以是任意对象,所以可以被对象调用的方法定义Object类中。

  生产者-消费者问题:

 class Resource{
private String name;
private int count = 1;
private boolean flag = false; public synchronized void set(String name){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name + " ~~ " + count++;
System.out.println(Thread.currentThread().getName() + "..生产者.." + this.name);
flag = true;
this.notifyAll();
} public synchronized void out(){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "....消费者...." + this.name);
flag = false;
this.notifyAll();
}
} class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r = r;
}
public void run(){
while(true){
r.set("商品");
}
}
} class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
} public class Demo{
public static void main(String[] args) {
Resource r = new Resource();
Thread t1 = new Thread(new Producer(r));
Thread t2 = new Thread(new Producer(r));
Thread t3 = new Thread(new Consumer(r));
Thread t4 = new Thread(new Consumer(r));
t1.start();
t2.start();
t3.start();
t4.start();
}
}

 对于多个生产者和消费者。定义while判断标记的原因:让被唤醒的线程再一次判断标记。

             定义notifyAll的原因:需要唤醒对方线程。如果只用notify,容易                                        出现只唤醒本方线程的情况。导致程序中的所有线程都等待。

生产者-消费者(升级版):

 import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; class Resource{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition(); public void set(String name) throws InterruptedException{
lock.lock();
try{
while(flag){
condition_pro.await();
}
this.name = name + " ~~ " + count++;
System.out.println(Thread.currentThread().getName() + "..生产者.." + this.name);
flag = true;
condition_con.signal();
}finally{
lock.unlock();
}
} public void out() throws InterruptedException{
lock.lock();
try{
while(!flag){
condition_con.await();
}
System.out.println(Thread.currentThread().getName() + "....消费者...." + this.name);
flag = false;
condition_pro.signal();
}finally{
lock.unlock();
}
}
} class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r = r;
}
public void run(){
while(true){
try {
r.set("商品");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r = r;
}
public void run(){
while(true){
try {
r.out();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public class Demo{
public static void main(String[] args) {
Resource r = new Resource();
Thread t1 = new Thread(new Producer(r));
Thread t2 = new Thread(new Producer(r));
Thread t3 = new Thread(new Consumer(r));
Thread t4 = new Thread(new Consumer(r));
t1.start();
t2.start();
t3.start();
t4.start();
}
}

 JDK1.5中提供了多线程升级解决方案。将同步Synchronized替换成Lock操作。将Object中的wait、notify、notifyAll替换成了Condition对象,该对象可以Lock锁进行获取。

 如何停止线程:stop方法已经过时,只能让run方法结束。开启多线程运行,运行代码通常是循环结构。只要控制住循环,就可以让run方法结束,也就是线程结束。

 特殊情况:当线程处于冻结状态。就不会读取到标记,那么线程就不会结束。当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除。强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。

 Thread类提供该方法interrupt();

 class StopThread implements Runnable{
private boolean flag = true;
public synchronized void run(){
while(flag){
try{
wait();
}catch(InterruptedException e){
System.out.println(Thread.currentThread().getName() + "...exception");
}
System.out.println(Thread.currentThread().getName() + "...run");
}
}
public void changeFlag(){
flag = false;
}
} public class Demo{
public static void main(String[] args) {
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start(); int num = 0;
while(true){
if(num++ == 60){
t1.interrupt();
t2.interrupt();
st.changeFlag();
break;
}
System.out.println(Thread.currentThread().getName() + "....." + num);
}
System.out.println("over");
}
}

输出结果:

...
...
main.....59
main.....60
over
Thread-0...exception
Thread-0...run
Thread-1...exception
Thread-1...run

 守护线程:即后台线程。线程对象.setDaemon(true)

 当正在运行的线程都是守护线程时(即前台线程全结束),JVM退出。该方法必须在启动线程前调用。

 Join方法:线程对象.join(),当A线程执行到了B线程的.join()方法,A就会等待。等B线程都执行完,A才会执行。join可以用来临时加入线程执行。

 yield方法:暂停当前正在执行的线程对象,并执行其他线程。