一、通过继承Thread类方式创建线程
-
步骤:创建一个Thread类,或者一个Thread子类的对象,即通过继承Thread类的方式创建线程类,重写run()方法。
-
例子:线程1和线程2竞争获取cpu资源,两者获得cpu资源具有不确定性,是随机获取资源的
package com.imooc.thread;
class MyThread extends Thread{
MyThread(String name){
super(name);
}
public void run() {
for(int i = 0; i<10;i++) {
System.out.println(getName() + "正在执行" + i);
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程1");
MyThread mt2 = new MyThread("线程2");
mt1.start();
mt2.start();
}
}
二、测试Thread类的join() 和 join(x ms)方法
-
带参数的join方法:public final void join(long millis)
-
作用:调用join(x)方法的线程,优先执行x毫秒,x时间一过,丧失优先级,其他线程可以竞争cpu资源执行。
package com.imooc.thread;
class MyThread2 extends Thread{
public void run() {
for(int i =1;i<=300;i++) {
System.out.println(getName()+"线程真正执行" + i +"次");
}
}
}
public class JoinDemo {
public static void main(String[] args) {
MyThread2 mt = new MyThread2();
mt.start();
try {
mt.join(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=1;i<=20;i++) {
System.out.println("主线程执行第" + i +"次");
}
int main = Thread.currentThread().getPriority();
System.out.println(main);
mt.setPriority(Thread.MAX_PRIORITY);
}
}
三、通过实现Runnable接口创建线程
步骤(三步):类实例化,根据实例化的对象创建线程类,线程子类调用start方法
package com.imooc.runnable;
public class PrintRunnable implements Runnable {
int i = 1;
public void run() {
while(i<=10) {
System.out.println(Thread.currentThread().getName() + "正在运行" + (i++));
}
}
public static void main(String[] args) {
PrintRunnable pr = new PrintRunnable();
Thread t1 = new Thread(pr);
t1.start();
Thread t2 = new Thread(pr);
t2.start();
}
}
四、线程间的通信和同步

package com.imooc.queue;
public class Consumer implements Runnable{
Queue queue;
Consumer(Queue queue){
this.queue=queue;
}
@Override
public void run() {
while(true){
queue.get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.imooc.queue;
public class Producer implements Runnable{
Queue queue;
Producer(Queue queue){
this.queue=queue;
}
@Override
public void run() {
int i=0;
while(true){
queue.set(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.imooc.queue;
public class Queue {
private int n;
boolean flag=false;
public synchronized int get() {
if(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费:"+n);
flag=false;
notifyAll();
return n;
}
public synchronized void set(int n) {
if(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产:"+n);
this.n = n;
flag=true;
notifyAll();
}
}
package com.imooc.queue;
public class Test {
public static void main(String[] args) {
Queue queue=new Queue();
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}