Java 线程基础
一 两种创建线程的基本方式
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(name + "" + i);
}
}
}
public class MyThread1implements Runnable {
private String name;
public MyThread1(String name) {
this.name = name;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(name + "" + i);
}
}
}
public classThreadTest {
public static voidmain(String[] args) {
/*MyThread myThread = newMyThread("A");
MyThread myThread2 = newMyThread("B");
myThread.start();
myThread2.start();*/
MyThread1 myThread3 = newMyThread1("C");
MyThread1 myThread4 = newMyThread1("D");
Thread t1 = new Thread(myThread3);
Thread t2 = new Thread(myThread4);
t1.start();
t2.start();
}
}
二 线程的状态
三 线程中常用的方法
public classRunnableDemo implements Runnable {
private String name;
publicRunnableDemo(String name) {
this.name = name;
}
@Override
public void run() {
for(int i = 0; i < 500;i++) {
System.out.println(name + "" + Thread.currentThread().getName() + "" + i);
}
}
}
public class DemoTest{
public static voidmain(String[] args) {
RunnableDemo rd = newRunnableDemo("A");
RunnableDemo rd1 = newRunnableDemo("B");
Thread thread = new Thread(rd);
//Thread thread1 = new Thread(rd1);
thread.start();
for(int i = 0; i < 500;i++) {
if(i == 10) {
try {
thread.join();
} catch(InterruptedException e) {
// TODOAuto-generated catch block
e.printStackTrace();
}
}
System.out.println("main" + "" + i);
}
System.out.println(thread.isAlive());
//System.out.println(thread.isAlive());
/*thread1.start();*/
}
}
public classRunnableDemo implements Runnable {
private String name;
publicRunnableDemo(String name) {
this.name = name;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// TODOAuto-generated catch block
e.printStackTrace();
}
System.out.println(name + "" + Thread.currentThread().getName() + "" + i);
}
}
}
四 同步代码块
public classMyThreadDemo implements Runnable {
private int ticket = 5;
//资源共享的时候需要用到同步
@Override
public void run() {
for(int i = 0; i < 10; i++) {
synchronized (this) {
if(ticket > 0) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("车票:" + ticket--);
}
}
}
}
//public synchronized voidbuyTicket(){}//同步方法
}
public classMyThreadDemoTest {
public static voidmain(String[] args) {
MyThreadDemo m = newMyThreadDemo();
Thread t = new Thread(m);
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
t.start();
t1.start();
t2.start();
}
}
五 线程的生命周期