(1)线程睡眠
public class ThreadSleep1Test {
public static void main(String[] args) {
ThreadSleep threadsleep = new ThreadSleep();
threadsleep.start();
try {
Thread.sleep(1000);
threadsleep.setFlag(false);
System.out.println("main线程启动了");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static class ThreadSleep extends Thread{
private boolean flag = true;
@Override
public void run() {
//新线程的测试
while(flag){
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//100毫秒
}
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
}
//打印结果
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
main线程启动了
通过主线程把对参数传递给新创建的线程,是通过新创建的线程类进行传递参数的
(2)join
使用join把一个线程加入到另一个线程上,也就是把多线程按照单线程的方式处理,也就不会出现线程并行的情况了
public class ThreadJoinTest {
public static void main(String[] args) throws InterruptedException {
ThreadJoin join = new ThreadJoin();
Thread thread = new Thread(join, "newthread");
thread.start();
thread.join();//讲newthread线程合并到主线程上,也就是相当于单线程处理了,不会出现newthread和main两个线程交错打印的情况
for (int i = 0; i <5; i++) {
Thread.sleep(100);
System.out.println("线程"+Thread.currentThread().getName());
}
}
static class ThreadJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程"+Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//运行结果,因为把新创建的线程join到了主线程上了,也就不会出现交错打印的情况
线程newthread
线程newthread
线程newthread
线程newthread
线程newthread
线程main
线程main
线程main
线程main
线程main
(3)yelid()方法
该方法是让当前线程让出cpu,让其他线程使用,当其他线程不在使用的时候自己再使用的时候该线程再继续使用
public class ThreadYieldTest {
public static void main(String[] args) throws InterruptedException {
YieldTest test1 = new YieldTest("t1");
YieldTest test2 = new YieldTest("t2");
test1.start();//线程1启动
test2.start();//线程2启动
Thread.yield();
for (int i = 1; i <= 5; i++) {
Thread.sleep(100);
System.out.println("主线程"+Thread.currentThread().getName());
}
}
static class YieldTest extends Thread{
//如果用到了有参数的构造方法,需要在子类中创建的该构造方法的
public YieldTest(String name){
super(name);
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName()+":"+i);
if (i%2==0) {
// Thread.yield();
}
}
}
}
}