创建线程的两种方法:
(1)implements Runnable
(2)extends Thread 第一种方法应用范围更广,他的start方法 Thread s1=new Thread(new Thread_name); s1.start();
设置优先级
helloThread_2.setPriority(Thread.NORM_PRIORITY+4);线程默认优先级为5,优先级越高,越先被执行,并不能确保真正的执行顺序;
使用sleep方法暂时暂停线程
睡眠完后不一定立即执行,只是能够参与竞争。
Thread.sleep(time);毫秒级别,调用此方法一定会抛出异常,使用try {....} catch{.....};
不能在run()后面 throws IOException
用throws抛出异常时,如果向主调处抛异常的方法是从父类继承的或者是实现的接口的一个方法。那么覆盖其方法时,如果原方法没有抛异常,则子类中这个方法也不能抛出异常。就用try catch进行处理:
Thread.yield线程的让步,该线程停留在这
Thread dd=new....;
dd.join();
阻塞时将当前线程暂停,直至调用join函数所对应的线程执行完毕,才执行其他线程(重新争夺cpu):
//车站卖票问题
synchronized 让他管辖的代码部分,要么全部执行,要么全部不执行
既可以修饰函数, 也可以修饰代码块--------synchronized(String)随便传入一个string ,修饰函数不需要字符串,相当于this。
public class Ticket {
public static void main(String[]args) {
TicketThread xx=new TicketThread();
Thread s1=new Thread(xx);
s1.start();
Thread s2=new Thread(xx);
s2.start();
}
}
class TicketThread implements Runnable{
public int num=100;
String aa=new String("aa");
public void run() {
while(true) {
synchronized (aa) {
if(num>0){
System.out.println(Thread.currentThread().getName()+"正在卖第"+(101-num)+"张票");
--num;
}
else {
break;
}
}
}
}
}
生产者消费者问题
class Ck{
char [] name=new char[8];
int number=0;
public synchronized void shengchan(char aa) {
while(number==name.length) {
try {
this.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
this.notify();
name[number]=aa;
number++;
System.out.println("当前正在生产第"+number+"个产品,名字为"+aa);
}
public synchronized void xiaofei() {
while(number==0) {
try {
this.wait();
}
catch (Exception e) {
// TODO: handle exception
}
}
this.notify();
char aa=name[number-1];
System.out.println("当前正在消费第"+number+"个产品,名字为"+aa);
number--;
}
}
class Xf implements Runnable{
Ck ck=new Ck();
public Xf(Ck ck) {
this.ck=ck;
}
public void run() {
for(int i=0;i<26;i++)
ck.xiaofei();
}
}
class Sc implements Runnable{
Ck ck=new Ck();
public Sc(Ck ck) {
this.ck=ck;
}
public void run() {
char aa='A';
for(int i=0;i<26;i++) {
aa=(char)('A'+i);
ck.shengchan(aa);
}
}
}
public class Product {
public static void main(String[]args) {
Ck ck=new Ck();
Thread s1=new Thread(new Sc(ck));
Thread s2=new Thread(new Xf(ck));
s1.start();
s2.start();
}
}