java基础7
IO流
1、InputStream
(1)int read()
从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。
(2)int read(byte[] b)
从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取的字节数。
(3)int read(byte[] b, int off,int len)
将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1.
(4)public void close() throws IOException关闭此输入流并释放与该流关联的所有系统资源
-
public class MyThreadWithExtends extends Thread {
-
-
private int tickets = 10;
-
-
@Override
-
public void run() {
-
-
for (int i = 0; i <= 100; i++) {
-
if(tickets>0){
-
System.out.println(Thread.currentThread().getName()+"--卖出票:" + tickets--);
-
}
-
}
-
}
-
-
-
public static void main(String[] args) {
-
MyThreadWithExtends thread1 = new MyThreadWithExtends();
-
MyThreadWithExtends thread2 = new MyThreadWithExtends();
-
MyThreadWithExtends thread3 = new MyThreadWithExtends();
-
-
thread1.start();
-
thread2.start();
-
thread3.start();
-
-
//每个线程都独立,不共享资源,每个线程都卖出了10张票,总共卖出了30张。如果真卖票,就有问题了。
-
}
-
-
}
-
package multithreading;
-
-
public class MyThreadWithImplements implements Runnable {
-
-
private int tickets = 10;
-
-
@Override
-
public void run() {
-
-
for (int i = 0; i <= 100; i++) {
-
if(tickets>0){
-
System.out.println(Thread.currentThread().getName()+"--卖出票:" + tickets--);
-
}
-
}
-
}
-
-
-
public static void main(String[] args) {
-
MyThreadWithImplements myRunnable = new MyThreadWithImplements();
-
这其中的Runnable仅仅是个业务,只不过放在Thread中,交给线程处理
-
Thread thread1 = new Thread(myRunnable, "窗口一");
-
Thread thread2 = new Thread(myRunnable, "窗口二");
-
Thread thread3 = new Thread(myRunnable, "窗口三");
-
-
thread1.start();
-
thread2.start();
-
thread3.start();
-
}
-
-
}
其他方法
1、public final boolean isAlive()判断线程是否还活着
2、public final String getName()返回线程的名称
3、public final void setName(String name)设置该线程名称
4、public static Thread currentThread()返回当前线程。在Thread子类中就是this,通常用于主线程和Runnable实现类
线程的优先级
线程的优先级控制
-
MAX_PRIORITY(10);
-
MIN _PRIORITY (1);
-
NORM_PRIORITY (5);
涉及的方法:
-
getPriority() :返回线程优先值
-
setPriority(int newPriority) :改变线程的优先级
线程创建时继承父线程的优先级
说明:优先级只是代表概率,不代表绝对的先后顺序
解决办法线程问题:synchronized+wait+notify
-
线程安全问题:同步
-
透支消费问题:线程通信
-
仓库容量有限问题:线程通信
wait() 与 notify() 和 notifyAll(),Java.lang.Object提供的这三个方法。
-
public final void wait():该线程发布对此监视器的所有权(即释放锁)并等待,直到其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来。然后该线程将等到重新获得对监视器的所有权后才能继续执行。
-
public final void notify():唤醒在此对象监视器(锁)上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。
-
public final void notifyAll():唤醒在此对象监视器(锁)上等待(wait)的所有线程。
class HouseWare {
private final int MAX = 10;
private int num;
public synchronized void put() {
if(num>=MAX){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println("工人生产了一台电视机,现在库存为:" + num);
this.notify();
}
public synchronized void take() {
if(num<=0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num--;
System.out.println("消费者买走了一台电视机,现在库存为:" + num);
this.notify();
}
}