package test;
我们提供的服务有:网站制作、成都网站建设、微信公众号开发、网站优化、网站认证、昆明ssl等。为成百上千企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的昆明网站制作公司
public class Test33{
private static int state = 1;
private static int num1 = 1;
private static int num2 = 2;
public static void main(String[] args) {
final Test33 t = new Test33();
new Thread(new Runnable() {
@Override
public void run() {
while(num1100){
//两个线程都用t对象作为锁,保证每个交替期间只有一个线程在打印
synchronized (t) {
// 如果state!=1, 说明此时尚未轮到线程1打印, 线程1将调用t的wait()方法, 直到下次被唤醒
if(state!=1){
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 当state=1时, 轮到线程1打印5次数字
for(int j=0; j1; j++){
System.out.println(num1);
num1 += 2;
}
// 线程1打印完成后, 将state赋值为2, 表示接下来将轮到线程2打印
state = 2;
// notifyAll()方法唤醒在t上wait的线程2, 同时线程1将退出同步代码块, 释放t锁
t.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(num2100){
synchronized (t) {
if(state!=2){
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=0; j1; j++){
System.out.println(num2);
num2 += 2;
}
state = 1;
t.notifyAll();
}
}
}
}).start();
}
}
public class TestThreadOutput {
public static void main(String[] args) {
OutputInt opi=new OutputInt();
Thread th1=new Thread(opi);
Thread th2=new Thread(opi);
th1.start();
th2.start();
}
}
class OutputInt implements Runnable{
public void run() {
for(int i=10;i=15;i++){
System.out.print(i+",");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
请采纳答案,支持我一下。
class MyThread implements Runnable {
private String name;
private int sum=100;
public MyThread(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i 100; i++) {
if(sum0){
System.out.println("线程开始:" + this.name + ",sum=" + sum--);
}}
}
};
public class ThreadDemo01 {
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程a");
new Thread(mt1).start();
new Thread(mt1).start();
}
}