public class LearnThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
class Thread1 extends Thread{
private String name;
public Thread1(String name) {
this.name=name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 : " + i);
try {
sleep((int) Math.random() * 10);//Math.Random()返回带正号的double值,取值范围是[0.0,1.0)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Thread1 mTh1=new Thread1("A");
Thread1 mTh2=new Thread1("B");
mTh1.start();
mTh2.start();
//Runnable
class Thread3 implements Runnable{
private String name;
public Thread3(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 : " + i);
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
new Thread(new Thread3("C")).start();
new Thread(new Thread3("D")).start();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
class Thread1 extends Thread{
private String name;
public Thread1(String name) {
this.name=name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 : " + i);
try {
sleep((int) Math.random() * 10);//Math.Random()返回带正号的double值,取值范围是[0.0,1.0)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Thread1 mTh1=new Thread1("A");
Thread1 mTh2=new Thread1("B");
mTh1.start();
mTh2.start();
//Runnable
class Thread3 implements Runnable{
private String name;
public Thread3(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 : " + i);
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
new Thread(new Thread3("C")).start();
new Thread(new Thread3("D")).start();
}
}
多线程:
线程中加入等待其他线程join();
退让,让cpu时间给同等优先级的线程,退让时间不定:yield()
线程优先级设置:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Thread4 t1 = new Thread4("t1");
Thread4 t2 = new Thread4("t2");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
sleep(100L)意思为:占用CPU,线程休眠100毫秒
wait(100L)意思为:不占用CPU,线程等待100毫秒