46 等待唤醒机制
wait(); 休眠
notify(); 唤醒线程池中第一个休眠的线程
notifyAll(); 唤醒所有休眠线程
都是用在同步中,因为要对持有监视器(锁)的线程操作
所以要使用在同步中,因为只有同步才有锁.
为什么这些操作线程的方法要定义在Object类中?
因为这些方法在操作同步中线程时,都必要要标识它们所操作线程持有的锁.
等待和唤醒必须是在同一把锁上,锁可以是任意对象.
package pack;
class Demo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res
{
private String name;
private String sex;
private boolean flag = false; //轮流读取
public synchronized void set(String name,String sex) //锁是this
{
if(flag)
{
try
{
this.wait(); //等待唤醒1
}
catch(Exception e)
{
e.printStackTrace();
}
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out()
{
if(!flag)
{
try
{
this.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println(name+" "+sex);
flag = false;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r; //要操作同一个资源 传入就可以了
}
public void run()
{
int x = 0;
while(true)
{
if(x%2==1)
{
r.set("lili","female");
}
else
{
r.set("李雷","男");
}
++x;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r= r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
47 生产者消费者代码
package pack;
class Demo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
}
}
class Res
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
if(flag)
{
try
{
this.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
this.name = name + "--" +count++;
System.out.println(Thread.currentThread().getName() +" 生产者 " + this.name);
flag = true;
this.notify();
}
public synchronized void out()
{
if(!flag)
{
try
{
this.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " 消费者 " + this.name);
flag = false;
this.notify();
}
}
class Producer implements Runnable
{
private Res res;
Producer(Res res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.set("商品");
}
}
}
class Consumer implements Runnable
{
private Res res;
Consumer(Res res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
48 多个生产者消费者: 使用while循环与notifyAll
package pack;
class Demo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Producer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
}
}
class Res
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)
{
try
{
this.wait();
}
catch(Exception 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(Exception e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " 消费者 " + this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Res res;
Producer(Res res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.set("商品");
}
}
}
class Consumer implements Runnable
{
private Res res;
Consumer(Res res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
49 当线程处于冻结状态,线程就不会读取到标记,那么线程就不会结束
interrupt() 方法:清除线程的中断状态,强制恢复到运行状态中来,并获取一个 InterruptedException 异常
当没有指定的方式让冻结状态的线程恢复到运行状态时,这时需要对冻结进行清除,强制让线程恢复到运行状态.
package pack;
class Demo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
t1.start();
Thread t2 = new Thread(st);
t2.start();
int num = 0;
while(true)
{
if(num++ == 60)
{
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName() + " " +num);
}
}
}
class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while(flag)
{
try
{
wait();
}
catch(Exception e)
{
e.getMessage();
flag = false;
}
System.out.println(Thread.currentThread().getName() + "...");
}
}
public void setFlag(boolean b)
{
flag = b;
}
}
50 setDaemon() 守护线程
1 在启动前设置为守护线程
2 当所有的线程是守护线程时,虚拟机退出.
51 join() 获取CPU执行权
当A线程执行到了B线程的.join方法时,A就会等待
等B线程执行完,A才会执行.
主要是用在中途加入线程时.
52 优先级 可以设置 1~10
MAX_PRIORITY 10
MIN_PRIORITY 1
MORE_PRIORITY 5
setPriority() 设置优先级
package pack;
class Demo
{
public static void main(String[] args) throws Exception
{
StopThread st = new StopThread();
Thread t1 = new Thr ead(st);
Thread t2 = new Thread(st);
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t1.join();
for(int num = 0;num<31;num++)
{
System.out.println(Thread.currentThread().getName() + " " +num);
}
}
}
53 释放执行权 yield() 静态方法
暂停当前正在执行的线程对象,并执行其他线程。
class StopThread implements Runnable
{
public void run()
{
for(int x=1 ;x<31;x++)
{
System.out.println(Thread.currentThread().getName() + " "+ Thread.currentThread().toString() + "..." + x);
Thread.yield();
}
}
}
54 String类
最大的特点是一旦初始化就不可改变
package pack;
class Demo
{
public static void main(String[] args)
{
String s1 = "abc";
s1 = "kk";
System.out.println(s1);
}
}
s1是类类型变量 "abc"是一个对象
这个程序中s1变了 但"abc"本身没有变
String类的比较 .equals()
package pack;
class Demo
{
public static void main(String[] args)
{
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //true String 类复写了equals方法 比较字符串是否相同
}
}
S1和S2有何区别:
S1代表一个对象 S2有两个对象
35 常量对象
S1 S3指向同一个对象 "abc"处于常量池中
package pack;
class Demo
{
public static void main(String[] args)
{
String s1 = "abc";
String s2 = new String("abc");
String s3 = "abc";
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //true
}
}
36 常见的操作
1) 获取
1.1获取长度 int length()
1.2根据位置获取位置上的某个字符 char charAt(int index)
1.3获取位置 (未找到返回-1)
indexOf(int ch) 返回ch在字符串中第一次出现的位置
indexOf(int ch,int fromIndex) 从fromIndex开始 返回ch在字符串中第一次出现的位置
indexOf(String str) 返回str在字符串中第一次出现的位置
indexOf(String str,int fromIndex) 从fromIndex开始 返回str在字符串中第一次出现的位置
int lastIndexOf(int ch)
int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。
2)判断
2.1 字符串是否包含某个子串
boolean contains(str);
int indexOf(String str) 也可以用于对指定字符串的判断是否包含 -1表不包含
2.2 字符串中是否有内容
boolean isEmpty();
2.3 字符串是否以指定内容开头
boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开始。
boolean startsWith(String prefix, int toffset)
测试此字符串从指定索引开始的子字符串是否以指定前缀开始
2.4 字符串是否以指定内容结尾
boolean endsWith(String suffix)
测试此字符串是否以指定的后缀结束。
2.5 判断字符串内容是否相同
boolean equals(str) 复写object中的equals
2.6 判断字符串内容是否相同,并忽略大小写
boolean equalsIgnoreCase();
3) 转换
3.1 将字符数组转成字符串
构造函数 String(char[],offser,count)将字符数组中的一部分转换成字符串
static String copyValueOf(char[] data)
返回指定数组中表示该字符序列的 String。
static String copyValueOf(char[] data, int offset, int count)
返回指定数组中表示该字符序列的 String
static String valueOf(char[] data)
3.2 将字符串转成字符数组 **
char[] toCharArray();
3.3 将字节数组转成字符串
String(byte[])
String(byte[],offset,count)
3.5 将基本数据类型转成字符串
static String valueOf(int)
static String vlause(double)
3+""
特殊:字符串和字节数组在转换过程中,是可以指定编码表的
4) 替换
String replace(oldchar,newchar);
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
String replace(oldstr,newstr);
5) 切割
String[] split(regex);
6) 子串 获取字符串中的一部分.
String substring(int beginIndex);
String substring(int beginIndex,int endIndex);
注意函数名全小写
7) 转换 去除空格 比较
7.1 讲字符串转换成大写或者小写
String toUpperCase();
String toLowerCase();
7.2 将字符串两端的多个空格去除
Strig trim();
7.3 对两个字符串进行自然顺序的比较
int compareTo(String);
>0 大
= 0 相等
<0 小
package pack;
class Demo
{
public static void method_get()
{
String str = "abcdefbef";
//长度
sop(str.length()); //9
//根据索引取字符
sop(str.charAt(1)); //b
//根据字符获取索引
sop(str.indexOf('b')); //1
sop(str.indexOf('b',2)); //6
sop(str.indexOf("ef")); //4
sop(str.indexOf("ef",6)); //7
sop(str.indexOf("m")); //-1 未找到
sop(str.lastIndexOf('f')); //最后一次出现的位置 8
}
public static void method_is()
{
String str = "ArrayDemo.java";
sop(str.isEmpty());//false
//判断文件名称是否是Array开头
sop(str.startsWith("Array"));//true
//是否以.java结尾
sop(str.endsWith(".java"));//true
//是否包含Demo
sop(str.contains("Demo"));//true
//判断字符串是否一样
sop(str.equals("ArrayDemo.java"));//true
//判断字符串是否一样 忽略大小写
sop(str.equalsIgnoreCase("arraydemo.java"));//true
}
public static void method_trans()
{
//将字符数组转化为字符串
char[] ar = {'a','b','c','d','e'};
String s1 = new String(ar);
String s2 = new String(ar,1,3); //从索引1开始 3个字符
sop(s1);//abcde
sop(s2);//bcd
String s3 = String.copyValueOf(ar);
sop(s3);//abcd
String s4 = String.copyValueOf(ar,1,3);
sop(s4);//bcd
//字符串转化成数组
String s5 = "abchnj";
char[] chs = s5.toCharArray();
sop(chs); //数组打印出的是地址
for(int i=0;i<chs.length;i++)
{
sop(chs[i]);
}
String s6 = String.valueOf(12300.0);
sop(s6);
String s7 = 123+"";
sop(s7);
}
public static void method_replace()
{
String s = "hello,java,java";
String s2 = s.replace("java","c++"); //返回一个新的字符串 其中原来的java全部替换为c++
sop(s2);
String s3 = s.replace('a','e'); //字符替换
sop(s3);
}
public static void method_split()
{
String s = "hello,java,java";
String[] arr = s.split(","); //双引号
for(int x=0;x<arr.length;x++)
{
sop(arr[x]);
}
}
public static void method_sub()
{
String s = "abcdefghij";
sop(s.substring(2)); //cdefghij 从开始位置到结尾
sop(s.substring(2,4)); //cd 从开始位置到结束位置之前 含头不含尾
}
public static void method_7()
{
String s = "abcdefg";
String up = s.toUpperCase();
sop(up);
String lower = s.toLowerCase();
sop(lower);
String s1 = " 12 3 ";
String tm = s1.trim(); //只能去除两端空格
sop(tm);
String s2 = "abc3";
String s3 = "aba2";
sop(s2.compareTo(s3)); //2
}
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
//method_get();
//method_is();
method_trans();
method_replace();
method_split();
method_sub();
method_7();
}
}
38 StringBuffer
是一个字符串缓冲区,是一个容器
特点:长度是可变化的,可以直接操作多个数据类型,通过toString变成字符串
1 增加
StringBuffer append(); 在后面插入
StringBuffer insert(index,data); 在指定位置插入
2 删除
StringBuffer delete(start,end)删除缓冲区的数据 含头不含尾
StringBuffer deleteCharAt(index) 删除指定位置的字符
3 查询
char charAt(int index); //索引处的字符
int indexOf(String str); //字符串第一次出现的地方
int lastIndexOf(String str) //字符串最后一次出现的地方
int length(); //长度
String substring(int start,int end); //返回子串,注意类型是String
4 修改
StringBuffer replace(start,end,str); // 使用给定 String 中的字符替换此序列的子字符串中的字符
void setCharAt(index,char); 将给定索引处的字符设置为 ch。
StringBuffer reverse() 将此字符序列用其反转形式取代
5 将字符从此序列复制到目标字符数组 dst。
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
package pack;
class Demo
{
public static void main(String[] args)
{
//增加
StringBuffer sb = new StringBuffer();
sb.append(34).append(true).append(56);
sb.insert(1,"qq");//在第一位插入qq
sop(sb.toString());//3qq4true56
//删除
sop("=========");
sb.delete(0,2); //删除0到1的数据.注意含头不含尾
sop(sb.toString()); //q4true56
sb.deleteCharAt(6); //删除编号为6的数据
sop(sb.toString()); //q4true6
sb.delete(0,sb.length()); // 清空缓冲区
sop(sb.toString());
//查询
sop("=========");
sb.append(123).append("abc").append(true);
sop(sb.toString());
sop(sb.charAt(2)); //3 2这个字符的位置
sop(sb.indexOf("123")); //0 返回字符串第一次出现的地方
sop(sb.indexOf("abc")); //3
sop(sb.length()); //10 长度
sop(sb.substring(1,5)); //23ab 从1到4位置的子串
sop("=========");
sop(sb.toString());
sb.replace(1,4,"java");// 1~3位置的子串替换为java
sop(sb.toString()); //1javabctrue
sb.setCharAt(0,'$');
sop(sb.toString());//$javabctrue
sb.reverse(); //反转
sop(sb.toString());//eurtcbavaj$
sop("=========");
//将字符从此序列复制到目标字符数组 dst。
char[] chs = new char[4];
sb.getChars(1,4,chs,1);
for(int x=0;x<chs.length;x++)
{
sop("chs["+x+"]="+chs[x]+";");
}
/**
chs[0]=
chs[1]=u
chs[2]=r
chs[3]=t
*/
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
39 StringBuilder
StringBuffer 是线程同步(要不提地判断锁)
StringBuilder 是线程不同步 ,比较快
以后开发建议时候是 StringBuilder,涉及到多线程的自己加锁
JDK升级三个因素: 1提高效率,2 简化书写 3提高安全性
使用方法和StringBuffer一样
40 基本数据类型对象包装类
byte Byte
short Short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
基本数据类型包装类的最常见作用,就是用于基本数据类型
和字符串类型间的转化
基本数据类型转字符串
1 基本数据类型+"" (最简单 推荐)
2 String.valueOf(基本数据类型)
3 基本数据类型.toString(基本数据类型值)
如 Integer.toString(34); //将34整数转换成"34"
字符串转基本数据类型: (重要)
基本数据类型
int n = Integer.parseInt("123");
xxx a = Xxx.parseXxx(String);
package pack;
class Demo
{
public static void main(String[] args)
{
sop("int max:"+Integer.MAX_VALUE);
sop("int size:"+Integer.SIZE);
String str = Integer.toString(123);
int num = Integer.parseInt(str);
sop(num+4); //127
long x = Long.parseLong("123123123123");
sop(x+1);
double d = Double.parseDouble("123.0123");
sop(d+1);
boolean b = Boolean.parseBoolean("true");
sop(b);
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
41 进制转换
//10进制转其他进制
Integer.toBinaryString(-6)
Integer.toOctalString(-6)
Integer.toHexString(-6)
//其他进制转10进制
int y = Integer.parseInt("170",8);
sop("0170="+y);
//16进制转10进制
y = Integer.parseInt("f10a",16);
sop("0xf10a="+y);
42 intValue()
Integer 转换成 int
package pack;
class Demo
{
public static void main(String[] args)
{
sop("int max:"+Integer.MAX_VALUE);
sop("int size:"+Integer.SIZE);
String str = Integer.toString(123);
int num = Integer.parseInt(str);
sop(num+4); //127
long x = Long.parseLong("123123123123");
sop(x+1);
double d = Double.parseDouble("123.0123");
sop(d+1);
boolean b = Boolean.parseBoolean("true");
sop(b);
//10进制转其他进制
sop(Integer.toBinaryString(-6));
sop(Integer.toOctalString(-6));
sop(Integer.toHexString(-6));
//其他进制转10进制
//8进制转10进制
int y = Integer.parseInt("170",8);
sop("0170="+y);
//16进制转10进制
y = Integer.parseInt("f10a",16);
sop("0xf10a="+y);
//Integer转化成整形
int z = new Integer("123").intValue();
sop(z);
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
43 比较
包装中重载了equals 所以是比较数值的是否相等
package pack;
class Demo
{
public static void main(String[] args)
{
Integer x = new Integer("123");
Integer y = new Integer(123);
sop("x==y:"+(x==y)); //false x y是两个不同对象类型
sop("x equals y:"+x.equals(y));//true 判断是否相等
//比较大小
Integer a = 123;
Integer b = 124;
sop("a?b:"+a.compareTo(b)); //-1
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
44 基本数据类型包装新特性
Integer x = 4; //自动装箱
package pack;
class Demo
{
public static void main(String[] args)
{
Integer x = 4; //自动装箱
x = x+4; //x.intValue()+4 先拆箱 运算完再装箱
Integer m = 128;
Integer n = 128;
sop("m==n?"+(m==n)); //false
Integer a = 127;
Integer b = 127;
sop("a==b?"+(a==b)); //true
//因为a 和b指向同一个Integer对象
//因为在byte范围内,对于新特性,如果该数值已经存在,不会开辟空间
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
45 Collection<E> 接口基本操作
容器中存放的是引用
package pack; //写在import前面
import java.util.*;
class Demo
{
public static void main(String[] args)
{
//创建容器
ArrayList al = new ArrayList();
//1添加元素
al.add("hello1");
al.add("hello2");
al.add("hello3");
al.add("hello4");
al.add("hello5");
//2获取个数,集合长度
sop(al.size()); //5
//3 打印原集合
sop(al); //[hello1, hello2, hello3, hello4, hello5]
//4 判断元素
sop("hello3是否存在:"+al.contains("hello2")); //true
sop("al是否为空:"+al.isEmpty()); //false
//是否包含
ArrayList al2 = new ArrayList();
al2.add("hello2");
al2.add("hello4");
al2.add("hello12345");
ArrayList al3 = new ArrayList();
al3.add("hello2");
al3.add("hello4");
sop("al是否包含al2中所有元素:"+al.containsAll(al2)); //false
sop("al是否包含al3中所有元素:"+al.containsAll(al3)); //true
//取交集
// boolean retainAll(Collection<?> c)
// 仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作
al2.retainAll(al3);
sop("al2与al3取交集:"+al2);
//5 删除
al.remove("hello2"); //删除元素
sop(al);//[hello1, hello3, hello4, hello5]
ArrayList del = new ArrayList();
del.add("hello4");
del.add("hello5");
al.removeAll(del); //删除指定集合中的元素
sop(al); //[hello1, hello3]
al.clear(); //清空
sop(al); //[]
sop("al是否为空:"+al.isEmpty()); //true
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
46 遍历
Iterator<E> iterator()返回在此 collection 的元素上进行迭代的迭代器。
boolean hasNext() 如果仍有元素可以迭代,则返回 true。
E next() 返回迭代的下一个元素。
void remove() 从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。
package pack;
import java.util.*;
class Demo
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add("hello1");
al.add("hello2");
al.add("hello3");
al.add("hello4");
al.add("hello5");
//获取迭代器
Iterator it = al.iterator();
//获取元素
while(it.hasNext())
{
sop(it.next()); //返回元素
}
//再次获取迭代器,发现新的迭代期指向首元素
Iterator dt = al.iterator();
sop(dt.next()); //hello1
//删除元素hello4
while(dt.hasNext())
{
if(dt.next().equals("hello4"))
{
dt.remove();
}
}
sop(al);
//遍历时更加节约内存的方式 for循环
for(Iterator it1 = al.iterator();it1.hasNext();)
{
sop(it1.next());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
47 List特有方法
Collection
|--List:元素有序,元素可以重复,有索引
|--Set:无序,不可重复
凡是可以操作脚标的方法都是该体系特有的方法
增
add(index,element)
addAll(index,Collection)
删
remove(index)
改
set(index,element)
查
get(index)
subList(from,to)
listIterator();