1 创建线程的两个基本 有 继承 thread, Runnable
thread
public class Test3 extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println("现在时间是"+new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
测试:
Test3 test =new Test3());
test.start(); //执行线程
try {
Thread.sleep(10000); //当前线程睡眠 1 0 秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.interrupt(); //线程停止
}
打印出
十秒的时间
runnable:
public class Test3 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println("现在时间是"+new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
测试:
Test3 test =new Test3());
test.start(); //执行线程
try {
Thread.sleep(10000); //当前线程睡眠 1 0 秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.interrupt(); //线程停止
}
打印 十秒的时间
几个基本方法的讲解
sleep() // 睡眠
wait() // 等待
notifyAll() //叫醒等待的线程
join() // 合并线程
synchronized 线程的同步(也可以说是锁)
下面一个消费生产实现
//定义产品类 如馒头
1.
public class Test5 {
//馒头编号
public int id;
public Test5(int id){
this.id = id;
}
}
2.
//定义装馒头的类
public class Test6 {
int index =0;
//定义一个馒头数组
Test5[] test = new Test5[6];
//装馒头
public synchronized void zhuang(Test5 mantou){
while(index == test.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
test[index]=mantou;
index++;
}
//去馒头
public synchronized Test5 qu(){
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return test[index];
}
}
3.生产类
public class Test7 implements Runnable {
Test6 test= null;
public Test7(Test6 test){
this.test =test;
}
//生成类
@Override
public void run() {
for(int i =0;i<20;i++){
Test5 test5 = new Test5(i);
test.zhuang(test5);
System.out.println("生产了:" + test5.id);
}
try {
Thread.sleep((int)(Math.random() *1000)); //随机数睡眠时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4.消费类
public class Test8 implements Runnable {
Test6 test= null;
public Test8(Test6 test){
this.test =test;
}
//消费类
@Override
public void run() {
for(int i =0;i<20;i++){
Test5 test5 =test.qu();
System.out.println("消费了: " + test5.id);
}
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
5 .测试
public static void main(String[] args) {
// TODO Auto-generated method stub
Test6 test = new Test6();
Thread tet = new Thread(new Test7(test));
Thread tet1 = new Thread(new Test8(test));
tet.start();
tet1.start();
}